我正在阅读一本名为 JavaScript 模式的书,但有一部分我认为这个人很困惑。
这家伙实际上在书中提到了 klass 设计模式,并在其中逐步开发了它。他首先提出了问题:
function inherit(C, P) {
C.prototype = P.prototype;
}
他说:
“这为您提供了短而快速的原型链查找,因为所有对象实际上共享相同的原型。但这也是一个缺点,因为如果继承链中某处的某个孩子或孙子修改原型,它会影响所有父母和祖父母。 ”
但是,我实际上尝试修改 Child 中的原型 say() 并且它对 Parent 没有影响,实际上 Child 仍然指向 Parent 并完全忽略了它自己的同名原型,这是有道理的,因为它指向不同的内存位置. 那么这家伙怎么能说出这种话呢?下面证明了我的观点:
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
任何子孙都不可能修改原型!
这就引出了我的第二点。他说,意外修改父原型沿继承链(我无法重现)的可能性问题的解决方案是打破父原型和子原型之间的直接链接,同时从原型链中受益。他提供以下解决方案:
function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
}
问题是这输出与其他模式相同的精确值:
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
空函数以某种方式破坏链接是没有意义的。事实上,Child 指向 F,F 又指向 Parent 的原型。所以他们都仍然指向同一个内存位置。上面演示了这一点,它输出与第一个示例相同的精确值。我不知道这位作者试图证明什么,以及为什么他提出的主张对我来说不是凝胶并且我无法复制。
感谢您的回复。