Skip to content

Extend Javascript Array

Aref Shafaei edited this page Jul 15, 2016 · 4 revisions

Problem

We want to create classes that are Array in nature, but have other methods and functionalities. In other words, we want to be able to add methods to Array class.

Solutions

1. Subclass Array

1.1. Extends

Using extends we can easily implement subclasses

Cons:


1.2. Implementing Extend Function

  • Using the goog.inherits impelementation. We should first add these lines of code to our project, then
function MyArray(){
  MyArray.base(this, 'constructor');
  
  this.extraFunction = function(){
    return "Extra";
  }
}
goog.inherits(MyArray, Array);

var arr = new MyArray();
arr.push(1,2);
console.log(arr.length);
console.log(arr.extraFunction());
  • We can also use this function that chirag has implemented. It's similar to goog.inherits.

Cons:

  • Extra helper functions should be added to the implementation.

1.3. Extend Alternatives

  • This article is pretty useful. In here you can find the implementation of them.

Cons:

  • All of them are a bit complicated and not worth the effort.
  • Using these we can just create some Array-like objects, not subclassing or extending Array class.

2. Delegation

Creating a wrapper class for arrays and implementing functions that we might need.

function MyArray(){
  this._data = [];
  Array.prototype.push.apply(this._data, arguments);
}
MyArray.prototype = {
  constructor: MyArray,
  length: function(){
    return this._data.length;
  },
  push: function(){
    return Array.prototype.push.apply(this._data, arguments);
  },
  get: function(index){
    return this._data[index];
  } 
}

Cons:

  • We have to define all the functions that we need.

3. Modify Array Prototype

Array.prototype.foo = function(){return "foo";}
var arr = [1,2,3];
console.log(arr.foo());

//using defineProperty:
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Cons:


4. Add Functions Directly

var arr = [1,2,3];
arr.foo = function(){return "so easy";}
console.log(arr.foo());

Cons:

  • It may cause some confusion with for(var i in arr).
  • We want a class that can be used in different places. This solution just works for a single object.