【问题标题】:Inheritance with Object.create in JavascriptJavascript 中 Object.create 的继承
【发布时间】:2013-11-04 14:12:39
【问题描述】:

我试图执行一个示例以了解继承。 B类继承自A。 成功执行的示例必须显示两个警报..

但是不工作.. 我以 MDN 为例..

代码如下

function A(a){
    this.varA =a;
}
A.prototype={
    varA:null,
    doSomething:function(){
        alert( "A invoked");
    }
}

function B(a,b){
    A.call(this,arguments);
    this.varB = b;
}

B.prototype = Object.create(A.prototype,
                            varB : {
                            value: null, 
                            enumerable: true, 
                            configurable: true, 
                            writable: true 
                            },
                          doSomething:{
                          value:function(){ 
                              A.prototype.doSomething.apply(this,arguments);
                              alert("B invoked);
                          },
                          enumerable:true,
                          configurable:true,
                          writable:true                    
                         });


                   var a =new A(1);
                   a.doSomething( );
                   var b = new B(1,2);
                   b.doSomething( );

【问题讨论】:

标签: javascript inheritance


【解决方案1】:

您在此行 alert("B invoked); 上缺少结束 "

编辑

我在这里更新了你的小提琴:http://jsfiddle.net/LmUXw/31/

您有一些拼写错误/语法错误。我可以建议您使用开发人员控制台(Chrome 中的F12,然后按console 选项卡)并查看记录到其中的错误。如果您单击行号链接,它会在控制台窗口中显示它,您可以看到是哪一行导致了问题。

【讨论】:

    【解决方案2】:

    我最初整理了代码,但我回滚了我的更改,因为在整理过程中我修复了一个错误!

    错误是:

    1. alert("B invoked); 需要关闭 "
    2. 在您的 Object.create 调用中,您缺少声明对象字面量的 {}

    代码应为:

    B.prototype = Object.create(A.prototype, {
        varB: {
            value: null,
            enumerable: true,
            configurable: true,
            writable: true
        },
        doSomething: {
            value: function () {
                A.prototype.doSomething.apply(this, arguments);
                alert("B invoked");
            },
            enumerable: true,
            configurable: true,
            writable: true
        }
    });
    

    请注意,此代码比您的代码要整洁得多。体面的缩进和格式(以及语法高亮)对理解代码和错误有很大的帮助。

    【讨论】:

    • @lonseomeday 将在下次发布时遵循缩进
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    相关资源
    最近更新 更多