move prototype extender into object module [broken, refactoring]

This commit is contained in:
Sami Samhuri 2011-06-05 18:06:04 -07:00
parent 0bae38cdb5
commit 2b7db269a3
2 changed files with 24 additions and 19 deletions

View file

@ -1,18 +0,0 @@
// batteries
// Copyright 2010 - 2011 Sami Samhuri <sami@samhuri.net>
exports.extend = function(obj, ext) {
Object.keys(ext).forEach(function(k) {
if (k in obj.prototype) return; // don't overwrite existing members
var wrapper = function() {
var fn = ext[k]
, args = [].slice.call(arguments)
;
args.unshift(this);
return fn.apply(this, args);
};
Object.defineProperty(obj.prototype, k, {
get: function() { return wrapper; }
});
});
};

View file

@ -4,10 +4,11 @@
var ObjectExt =
{ cmp: cmp
, extend: extend
, extendPrototype: extendPrototype
}
exports.extendNative = function() {
require('./ext').extend(Object, ObjectExt);
extendPrototype(Object, ObjectExt);
};
extend(module.exports, ObjectExt);
@ -24,3 +25,25 @@ function extend(a, b) {
a[k] = b[k];
});
}
function extendPrototype(obj, ext) {
Object.keys(ext).forEach(function(k) {
// TODO remove this and just warn? ... no good solution for conflicts, needs a human
if (k in obj.prototype) return; // don't overwrite existing members
var val = ext[k];
if (typeof val === 'function') {
val = methodWrapper(val);
}
Object.defineProperty(obj.prototype, k, { value: val });
});
}
// Make a wrapper than passes `this` as the first argument, Python style. All
// extension functions that can extend native types must follow this convention.
function methodWrapper(fn) {
return function() {
var args = [].slice.call(arguments);
args.unshift(this);
return fn.apply(this, args);
};
}