function Parent (arg1, arg2) {

    alert(arg1);

    this.member1 = arg1;
    this.member2 = arg2;
};

Parent.prototype.update = function () {

    // parent method update
};

function Child (arg1, arg2, arg3) {

    Parent.call(this, arg1, arg2);
    this.member3 = arg3;
};

Child.prototype = new Parent;

Child.prototype.update = function () {

    // overwritten method update
};

function init () {

    var childObject = new Child(false, false, false);
    childObject.update();
}


结果是两个警报


未定义



为什么警报会发生两次?我已经搜索过,但是还没有找到任何东西,也不知道要搜索什么。

结果应该是一个带有“ false”的警报,还是我错了?

多谢!

最佳答案

通过使用Parent的构造函数创建Child的原型,将调用构造函数,这是您对undefined的第一个警报。

为了创建仍然使用相同原型链但在创建原型时不调用父构造函数的原型,您需要在两者之间添加另一个步骤。

Child.prototype = (function() {
  var Base = function() {};
  Base.prototype = Parent.prototype;
  return new Base();
}());


这将创建一个匿名函数(称为Base),该函数的原型设置为Parent类的原型,然后将Child原型分配给一个新的Base,它将保留继承,但不会创建原型链时,不要调用Parent的构造函数。

09-30 16:30
查看更多