user1749974
user1749974

Reputation: 33

javascript inheritance, constructor called twice

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

The result are two alerts with

  1. undefined
  2. false

Why does the alert occurs two times? I already searched, but haven't found anything yet + don't know what to search for.

The result should be one alert with 'false', or am i wrong?

Thx alot!

Upvotes: 2

Views: 2333

Answers (2)

steveukx
steveukx

Reputation: 4368

By using the constructor of Parent to create the prototype for Child, the constructor is being called which is your first alert of undefined.

In order to create a prototype that still uses the same prototype chain, but doesn't call the parent constructor as the prototype is created, you need to add another step in between.

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

This will create an anonymous function (called Base) that has the prototype set to be the prototype of the Parent class, the Child prototype is then assigned to a new Base which will preserve the inheritance, but doesn't call the constructor of Parent as the prototype chain is created.

Upvotes: 4

Pulkit Goyal
Pulkit Goyal

Reputation: 5664

There is one alert when you create a new object of Parent Child.prototype = new Parent; and one when you create new object of child, var childObject = new Child(false, false, false);

Upvotes: 0

Related Questions