JavaScript继承,构造函数两次


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

结果是

的两个警报
  1. 未定义
  2. false

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

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

thx lot!

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

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

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

这将创建一个匿名函数(称为Base),该函数的原型集为Parent类的原型,然后将Child原型分配给新的Base,该原型将保留遗传,但不调用constructorParent作为原型链的创建。

创建父 Child.prototype = new Parent;的新对象时,有一个警报,当您创建孩子的新对象时,var childObject = new Child(false, false, false);

最新更新