-1

我试图执行一个示例以了解继承。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( );
4

2 回答 2

0

你错过了"这条线的关闭alert("B invoked);

编辑

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

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

于 2013-11-04T14:14:55.620 回答
0

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

错误是:

  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
    }
});

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

于 2013-11-04T14:22:46.580 回答