Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the prototype to create an Array with methods

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?

like image 272
ColBeseder Avatar asked Jan 30 '26 02:01

ColBeseder


1 Answers

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.

like image 75
satchmorun Avatar answered Jan 31 '26 16:01

satchmorun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!