I want to create a constructor function in javascript, which has a .prototype property and can be used with the new keyword to create new objects that have this property in their protochains. I also would like this object to subclass an Array.
I have been able to create an object that subclasses an Array (all needed functionality works)
I have not figured out how to make this object act as a function, so that it can be used as a constructor.
SubArray = function() {this.push.apply(this, arguments);};
SubArray.prototype = Object.create(Array.prototype);
SubArray.prototype.constructor = SubArray;
SubArray.prototype.last = function(){return this[this.length -1]};
var arr = new SubArray(0); // [0]
arr.push(1,2,3); // [0,1,2,3]
console.log(arr, arr.length); // [0,1,2,3], 4
arr.length = 2;
console.log(arr, arr.length); // [0,1], 2
console.log(arr.last()); // 2
console.log(arr instanceof Array); // true
console.log(arr instanceof SubArray); // true
I have read that by adding certain keys to the arr object it can be used as a constructor function.
I believe I would have to do something like this.
var arrayFunction = new SubArray(0); // [0]
arrayFunction.prototype = {
constructor: arrayFunction,
//shared functions
};
arrayFunction.call = function(){//this would be the constructor?};
arrayFunction.constructpr = function(){//I remember seeing this as well, but I can't find the original source where I saw this};
I would really appreciate any insight into how this can be done, thanks in advance for your help
I recall John Resig tried to subclass an Array for Jquery, but found it not possible.