I'm reading a book called JavaScript patterns but there's one part where I think the guy is confusing.
The guy actually led up in the book to the klass design pattern, where he developed it piece by piece. He first he presents the problem:
function inherit(C, P) {
C.prototype = P.prototype;
}
He says:
"This gives you short and fast prototype chain lookups because all objects actually share the same prototype. But that’s also a DRAWBACK because if one child or grandchild somewhere down the inheritance chain MODIFIES the prototype, it AFFECTS all parents and grandparents."
However, I actually tried to modify the prototype say() in Child and it had no affect on Parent and in fact Child still pointed to Parent and completely ignored its own prototype of same name, which makes sense since it's pointing to a different memory position. So how can the guy say something like that? Below proves my point:
function Parent(){}
Parent.prototype.say = function () {
return 20;
};
function Child(){
}
Child.prototype.say = function () {
return 10;
};
inherit(Child, Parent);
function inherit(C, P) {
C.prototype = P.prototype;
}
var parent = new Parent();
var child = new Child();
var child2 = new Child()
alert(child.say(); //20
alert(parent.say()); //20
alert(child2.say()); //20
It's impossible for any child or grandchild to modify the prototype!
This leads to my second point. He says the solution to the problem of the possibility of accidentially modifying parent prototypes down inheritance chain (which I can't reproduce) is to break the direct link between parent’s and child’s prototype while at the same time benefiting from the prototype chain. He offers the following as a solution:
function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
}
The problem is this outputs the same exact values as the other pattern:
function Parent(){}
Parent.prototype.say = function () {
return 20;
};
function Child(){
}
Child.prototype.say = function () {
return 10;
};
inherit(Child, Parent);
function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
}
var parent = new Parent();
var child = new Child();
var child2 = new Child()
alert(child.say(); //20
alert(parent.say()); //20
alert(child2.say()); //20
It doesn't make sense that an empty function somehow breaks a link. In fact, the Child points to F and F in turn points to the Parent's prototype. So they are ALL still pointing to the same memory position. This is demonstrated above, where it outputs the same exact values as the first example. I have no clue what this author is trying to demonstrate and why he makes claims that don't gel for me and that I can't reproduce.
Thanks for response.