javascript继承,构造函数调用两次

时间:2012-10-24 07:54:33

标签: javascript inheritance

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. 为什么警报会发生两次?我已经搜索过,但还没有找到任何东西+不知道要搜索什么。

    结果应该是一个警告“假”,或者我错了?

    很多!

2 个答案:

答案 0 :(得分:4)

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

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

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

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

答案 1 :(得分:0)

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

时创建新对象时有一个警告
相关问题