I want to return an array with extra methods. I usually do something like this:
MyConstructor = function(a, b, c){
var result = [a, b, c];
result.method1 = function(){
return a + b + c ;
}
return result ;
}
var obj = MyConstructor(2, 4, 6); // removed `new`
But as the number of methods and uses grow, I believe it will be easier to maintain (and more efficient) to use the prototype instead of defining these new (identical) anonymous functions each time but I can’t find a way to do this without those methods ending up on the Array.prototype.
Is this possible and if so, how?
One approach is to use a wrapper object, as in the answer by Shmiddty.
Or, if you don’t want to use a wrapper but want to modify the array directly, you could just augment it:
This way you don’t touch
Array.prototypeand your methods get added to the array without having to redefine them over and over. Note that they do, though, get copied to each array, so there is some memory overhead – it’s not doing prototypical lookup.Also, keep in mind that you could always just define functions that operate on arrays:
You don’t get the syntax sugar of
somearray.sum(), but thesumfunction is only ever defined once.It all just depends on what you need/want.