How can I create a custom array constructor, which is an extended version of the native Array constructor?
jQuery, for example, looks like an array with additional methods, such as $().addClass
. However, it didn't modify Array.prototype
, because new Array().hasClass
is undefined
.
So, how can I create an extended array implementation, without modifying Array.prototype
?
Example:
Employees( ... ) //-> [{name: 'John', age: 32}, {name: 'Bob', age: 29}];
Employees( ... ).byAge(32)//-> [{name: 'John', age: 32}];
// and
Array().byAge //-> undefined
jQuery is not a true Array implementation:
jQuery instanceof Array
is false!If you want to create a true instance of an array, and add custom methods, use this code. It uses
Function.prototype.bind
to call a constructor with an arbitrary number of parameters.The implementation behaves exactly as a true array, except at one point:
Array
constructor is called with a single argument, it's creating an array with a length of this argument.length
property.Code: http://jsfiddle.net/G3DJH/
The jQuery object is not an Array, nor does it "overwrite" the Array class. It is simply array-like.
You can see how jQuery accomplishes this by browsing the source; also see Array Like Objects in Javascript and Why Are Array-Like Objects Used in Javascript Over Native Arrays.
Using the costly
Object.setPrototypeOf
you can create an Object which inherits Array and supports automatic length changing,If the automatic properties of length aren't important to you, you can get away with Array-like Objects. These will appear like an Array in the Console if they have a length and a splice, but the length will not automatically change as you modify the Object so you can't simply set with bracket notation etc.