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:
// Define some special methods for use
var specialMethods = {
sum: function() {
var i = 0, len = this.length, result = 0;
for (i; i < len; i++) result += this[i];
return result;
},
average: function() {
return this.sum() / this.length;
}
};
function specialize(array) {
var key;
for (key in specialMethods) {
if (specialMethods.hasOwnProperty(key)) {
array[key] = specialMethods[key];
}
}
return array;
}
var arr = specialize([1, 2, 3, 4, 5]);
console.log(arr.sum()); // 15
console.log(arr.average()); // 3
This way you don't touch Array.prototype and 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:
function sum(array) {
var i = 0, len = array.length, result = 0;
for (i; i < len; i++) result += array[i];
return result;
}
You don't get the syntax sugar of somearray.sum(), but the sum function is only ever defined once.
It all just depends on what you need/want.
newkeyword is pointless for it. 2) #1 makes using the prototype chain pointless.MyConstructorserves no purpose. See my answer.