1

这段代码有什么问题?我正在尝试使用所有本机数组的函数来扩展类 foo 。

function foo(){
    Array.call(this);
 }

foo.prototype.addFruit=function(item){
    this.unshift(item);
}
foo.prototype=new Array();
foo.prototype.constructor=foo;

var c =new foo();

c.addFruit('Apple');


document.write(c.join('-'));
​
4

2 回答 2

2

您将方法添加addFruitprototypeof foo,然后覆盖了 the foo.prototype,因此缺少该方法(将方法放入原始原型后,原型更改为另一个对象)。

您应该更改代码的顺序,将prototypebefore add 方法分配给prototype.

foo.prototype=new Array();
foo.prototype.constructor=foo;

foo.prototype.addFruit=function(item){
    this.unshift(item);
};
于 2012-10-26T05:47:11.137 回答
2

在用. addFruit_prototypenew Array

而不是new Array,您应该使用Object.create(Array.prototype)因此您没有实际的 Array实例作为原型(使用length等),而只有一个从 Array 原型继承的对象。

Array.call(this)不幸的是不起作用。它返回一个新数组,该数组没有赋值,但它不做任何事情this。您可以通过this !== Array.call(this). 实际上,“子类”是不可能的Array- 请阅读http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array

于 2012-10-26T05:55:33.847 回答