【发布时间】:2014-02-06 17:26:19
【问题描述】:
在第 6 章(代码重用模式)中有以下示例:
// the parent constructor
function Parent(name) {
this.name = name || 'Adam';
}
// adding functionality to the prototype
Parent.prototype.say = function () {
return this.name;
};
// empty child constructor
function Child(name) {}
// inheritance magic happens here
inherit(Child, Parent);
在“经典模式#1 — 默认模式”部分中,inherit() 函数的实现是:
function inherit(C, P) {
C.prototype = new P();
}
在“使用模式 #1 时的缺点”一节中是以下示例:
var s = new Child('Seth');
s.say(); // "Adam"
我不明白以下作者的解释:
这不是你所期望的。孩子有可能通过 父的构造函数的参数,但你必须这样做 每次你需要一个新的孩子时继承,这是低效的, 因为你最终会一遍又一遍地重新创建父对象。
子级如何将参数传递给父级的构造函数?如果不通过隐藏的原型属性,如何在构造后更改子对象的原型?谁能给我一个例子,作者是什么意思?
【问题讨论】:
标签: javascript design-patterns inheritance prototype