【问题标题】:Javascript Inheritance: One Subclass gets the Prototype, the other doesn'tJavascript 继承:一个子类获得原型,另一个没有
【发布时间】:2013-12-25 06:03:24
【问题描述】:

我有一个SuperClass“类”,这个类将被SubClassASubClassB继承(通过原型链)。然而,虽然继承似乎对SubClassA 有效,但对SubClassB 却失败了。代码如下:

function SuperClass(childCell){
    this.childCell = childCell;
    this.children = new Array(9);
    for(i=0; i<9; i++) {
        this.children[i] = new this.childCell();
    }
}
function SubClassA(){
    this.num = 1;
}
SubClassA.prototype = new SuperClass(SubClassB);
function SubClassB(){
    this.num = 2;
}
SubClassB.prototype = new SuperClass(SubClassC);
function SubClassC(){
    this.num = 3;
}
var x = new SubClassA();

在这段代码中,我将x 设置为SubClassA 的一个对象,这又应该给我一个包含9 个SubClassB 对象的children 属性。它正确地做到了这一点,但反过来,每个 SubClassB 对象应该包含 9 个 SubClassC 对象。但是,在检查控制台后,我发现没有一个 SubClassB 对象实际上包含它应该通过原型继承的 childCellchildren 属性。

换句话说,x.children[0] 返回了SubClassB {num: 2},并且没有其他属性。

为什么SubClassA 的继承对SubClassB 不起作用?

【问题讨论】:

    标签: javascript oop inheritance prototype


    【解决方案1】:

    尝试重新排序您的声明示例,例如

    function Parent(childCell){
        this.childCell = childCell;
        this.children = new Array(9);
        for(var i=0; i<9; i++) {
            this.children[i] = new this.childCell();
        }
    }
    function ChildA(){
        this.num = 1;
    }
    function ChildB(){
        this.num = 2;
    }
    function ChildC(){
        this.num = 3;
    }
    
    ChildB.prototype = new Parent(ChildC);
    ChildA.prototype = new Parent(ChildB);
    

    您的问题 - 在向其添加原型之前调用 ChildB 构造函数

    更新

    @Bagavatu 创建对象时使用为构造函数设置的原型,然后您可以更改原型属性,此更改将应用​​于具有此原型的所有对象。
    在您的情况下,您更改了对原型的引用,因此它不适用于之前创建的对象。你可以用简单的例子来测试它

    function A() {this.cell = 10}
    function B() {this.num =1}
    
    var b1 = new B(); // b1 = {num:1}
    
    B.prototype = new A();
    var b2 = new B(); // b1 = {num:1}, b2 = {num:1, cell:10} 
    

    【讨论】:

    • 谢谢!这完美地工作。你能解释一下为什么我必须先定义 ChildB 原型吗?
    • @Bagavatu 试试看我更新的答案,我希望现在更清楚
    【解决方案2】:

    我通常不会深入挖掘。但是当我们在 javascript 中使用子类时,请遵循以下模式。

    function Superclass() { }
    Superclass.prototype.someFunc = function() { };
    
    function Subclass() { }
    Subclass.prototype = new Superclass();
    Subclass.prototype.anotherFunc = function() { };
    
    var obj = new Subclass();
    

    【讨论】:

    • 嗯……这对我有什么帮助?我相信我有这里写的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 2014-12-19
    • 1970-01-01
    相关资源
    最近更新 更多