From 2b7db269a3890c67d88d9836da5571023ade66e9 Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Sun, 5 Jun 2011 18:06:04 -0700 Subject: [PATCH] move prototype extender into object module [broken, refactoring] --- lib/ext.js | 18 ------------------ lib/object.js | 25 ++++++++++++++++++++++++- 2 files changed, 24 insertions(+), 19 deletions(-) delete mode 100644 lib/ext.js diff --git a/lib/ext.js b/lib/ext.js deleted file mode 100644 index b8a04a6..0000000 --- a/lib/ext.js +++ /dev/null @@ -1,18 +0,0 @@ -// batteries -// Copyright 2010 - 2011 Sami Samhuri - -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; } - }); - }); -}; diff --git a/lib/object.js b/lib/object.js index 58facd7..adfc2b0 100644 --- a/lib/object.js +++ b/lib/object.js @@ -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); + }; +}