-
Notifications
You must be signed in to change notification settings - Fork 3
Extend Javascript Array
Aref Shafaei edited this page Jul 18, 2016
·
4 revisions
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.
We decided to go with the easiest solution(Add Functions Directly) for now. If it wasn't sufficient enough, other options would be Delegation and Implementing Extend Function.
Using extends we can easily implement subclasses
Cons:
- It's not supported by most of the browsers.
- 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.
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.
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.
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:
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.