我想在 javascript 中创建一个构造函数,它具有 .prototype 属性,并且可以与 new 关键字一起使用来创建在其原型链中具有此属性的新对象。我也希望这个对象继承一个数组。
我已经能够创建一个子类化数组的对象(所有需要的功能都有效)我还没有弄清楚如何使这个对象充当一个函数,以便它可以用作构造函数。
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
我已经读过,通过向 arr 对象添加某些键,它可以用作构造函数。我相信我必须做这样的事情。
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};
我非常感谢您对如何做到这一点的任何见解,在此先感谢您的帮助