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
- undefined
- 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!
By using the constructor of
Parentto create the prototype forChild, the constructor is being called which is your first alert ofundefined.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.
This will create an anonymous function (called
Base) that has the prototype set to be the prototype of theParentclass, theChildprototype is then assigned to a newBasewhich will preserve the inheritance, but doesn’t call the constructor ofParentas the prototype chain is created.