当实例存储在数组中时,原型继承不起作用

Prototypal Inheritance Not Working When Instances Are Stored In An Array

本文关键字:原型 继承 不起作用 实例 存储 数组      更新时间:2023-09-26

我在上一个项目中偶然发现了一个非常奇怪的问题。我已经实现了继承如下:

    function Parent(){}
    Parent.prototype.hi = function(){
        alert("Parent: hi!");
    };
    Parent.prototype.bye = function(){
        alert("Parent: bye!");
    };
    function Child(){
        this.hi = function(){
            alert("Child: hi!");
        };
    }
    Child.prototype = new Parent();

通过这种方式,我可以只覆盖我在子构造函数中需要的函数,其余的将从父构造函数继承。

这个工作正常。下面是测试:

var test = function(){
    var p = new Parent();
    p.hi();
    p.bye();
    var c = new Child();
    c.hi();
    c.bye();
};
test();

输出是预期的:

Parent: hi!
Parent: bye!
Child: hi!
Parent: bye!

但是,当我将实例存储在数组中时,子实例中的bye函数没有被继承,并且会抛出一个错误。测试代码:

var anArray = [
    new Parent(),
    new Child()
];
var test2 = function(){
    for(var i = 0, m = null; i < anArray.length; i++){
        m = anArray[i];
        m.hi();
        m.bye();  //WTF not working for the child?
    }
};
test2();
输出:

Parent: hi!
Parent: bye!
Child: hi!
TypeError: m.bye is not a function

JSFiddle这里

我花了一个多小时盯着这段代码并调试它,但我看不出问题在哪里。最初的代码要复杂得多,功能也更多。我认为数组有问题,但我不想放弃它,因为我认为表驱动的方法是我想实现的最好的方法。

具有new Child实例的数组是在您让Child继承Parent之前创建的,并且仍然具有旧的原型(没有任何方法)。相比之下,c = new ChildChild.prototype = …赋值之后在test()函数中执行。

将数组声明/初始化移动到test2函数中。或者干脆把所有类的东西都移到上面。