While this below implementation seems good, because it allows a child to have its own copy of own members (without having ability to modify parent's own members), plus it uses the prototype chain, so properties won't be recreated for each object instantiation, it is not efficient because the Parent constructor is invoked twice (once for apply and new Parent instantiation):
function Parent(a,b,c,d){
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
Parent.prototype.say_a = function(){
return this.a;
}
Parent.prototype.say_b = function(){
return this.b;
}
Parent.prototype.say_c = function(){
return this.c;
}
Parent.prototype.say_d = function(){
return this.d;
}
Parent.prototype.not_going_to_be_copied = function(){
console.log(“This function will not be recreated from one object instantiation to the next, making it very efficient.”);
}
function Child(a,b,c,d){
Parent.apply(this,arguments);
}
Child.prototype = new Parent();
c = new Child("a","b","c","d");
console.log([c.say_a(),c.say_b(),c.say_c(),c.say_d()].join(" "));
Stoyan in Javascript Patterns mentions this alternative, which does not invoke Parent constructor at all:
Child.prototype = Parent.prototype;
However, he says a drawback to this is if one child or grandchild somewhere down the inheritance chain modifies the prototype, it affects all parents and grandparents.
However, I cannot reproduce that claim:
function Parent(){}
Parent.prototype.set_a = function(a){
this.a = a;
}
Parent.prototype.get_a = function(){
return this.a;
}
function Child(){}
Child.prototype = Parent.prototype;
var c = new Child();
var p = new Parent();
c.set_a("a");
console.log(c.get_a()); // a
p.set_a("b");
console.log(p.get_a()); // b
console.log(c.get_a()); // a
c.prototype = {};
console.log("after mod " + c.get_a()); // after mod a
console.log("after mod " + p.get_a()); // after mod b
c.get_a = function(){return "am I changing parent?"}
console.log(c.get_a()); // am I changing parent?
console.log(p.get_a()); // b
As you can see, no matter how I modify the prototype of Child, it does not affect the prototype of Parent. So am I missing something? Can the children's modification of prototype have affect on the Parent?