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 Arrayis false!If you want to create a true instance of an array, and add custom methods, use this code. It uses
Function.prototype.bindto call a constructor with an arbitrary number of parameters.The implementation behaves exactly as a true array, except at one point:
Arrayconstructor is called with a single argument, it’s creating an array with a length of this argument.lengthproperty.Code: http://jsfiddle.net/G3DJH/