【发布时间】:2012-05-31 04:16:43
【问题描述】:
我想在 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};
非常感谢您对如何做到这一点的任何见解,在此先感谢您的帮助
【问题讨论】:
-
一个更简单的问题可能是,可以通过添加call等方法将javascript对象变成构造函数吗?
-
——我对此表示怀疑。与
new一起使用的对象必须实现一个内部[[Construct]]方法(ES5 11.2.2),只有Functions 有这样的方法(它在Function.prototype 上)。 -
那很不幸,我想我必须满足于我现在所拥有的。如果这是一个答案,我会接受。