Reputation: 13853
I want to extend standard Objects such as String with prototypes. For example, add diff function for an Array. Good way of organization code in Node.js is modules, but how do this with prototype?
Example
Array.prototype.diff = function (a) {
return this.filter(function (i) {
return !(a.indexOf(i) > -1);
});
};
Upvotes: 4
Views: 1563
Reputation: 2035
** Due to my low rank I can not comment :( so I am writing an answer
It is a very bad practice to extend the native objects, please avoid this at all costs. Mootools has taken this approach, just google for "mootools collision" and see the issues that keep coming up.. Even though they have been moving away from it since version 1.2.4.
As soon as another library is extending the native objects (mapping, graphics libs sometimes do this from past experience) you get different code expecting different behavior out of those additions.
So in short, create another "Utility" class that houses these functions and include and use that instead.
Upvotes: -2
Reputation: 1375
I can not speak for nodejs, but Mozilla's JS modules are similar I guess and there I ran into the same problem once.
Thing is that each JS module (and nodejs modules probably as well) runs in its own JavaScript context, thus the Array constructor (and prototype) from different modules are not the same. They are completely different objects.
I would probably have a module with a helper function that adds the according changes to a given object. This means though, that you have to call the helper function from within every module that you want to use the extended Array prototype from.
ArrayHelperModule:
function extendArray(arrayConstructor)
{
arrayConstructor.prototype.diff = function (a) {
return this.filter(function (i) {
return !(a.indexOf(i) > -1);
});
};
}
exports.extendArray = extendArray;
Module that uses Array:
var ArrayHelperModule = require("ArrayHelperModule");
// extending the Array of this module
ArrayHelperModule.extendArray(Array);
// use it
var diff = [1, 2].diff([1]);
p.s. hope the code is correct this way ... i just typed it in here quickly
Upvotes: 4
Reputation: 3849
This worked for me.
Array.prototype.diff = function( compareArray ) {
return this.filter(
function( arrayItem ){
return this.indexOf( arrayItem ) == -1;
},
compareArray
);
};
You could also add a level to the prototype chain I guess but that would require more complexity and doesn't seem that useful yet.
P.s. I'm not sure how you were planning on using the filter function.
var a = [1,2,3,4];
var b = [3,4,5,6];
console.log( a.diff( b ) );
// Outputs:
[ 1, 2 ]
Upvotes: 0