JavaScript 中的原型继承
我一直在 YUI Theater 观看 Douglas Crockford 的演讲,我有一个关于 JavaScript 继承的问题...
Douglas 给出了这个例子来表明“Hoozit”继承自“Gizmo”:
function Hoozit(id) {
this.id = id;
}
Hoozit.prototype = new Gizmo();
Hoozit.prototype.test = function (id) {
return this.id === id;
};
为什么他写 Hoozit.prototype = new Gizmo()
而不是 Hoozit.prototype = Gizmo.prototype
?
这两者有什么区别吗?
I've been watching Douglas Crockford's talks at YUI Theater, and I have a question about JavaScript inheritance...
Douglas gives this example to show that "Hoozit" inherits from "Gizmo":
function Hoozit(id) {
this.id = id;
}
Hoozit.prototype = new Gizmo();
Hoozit.prototype.test = function (id) {
return this.id === id;
};
Why does he write Hoozit.prototype = new Gizmo()
instead of Hoozit.prototype = Gizmo.prototype
?
Is there any difference between these two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
原因是使用 Hoozit.prototype = Gizmo.prototype 意味着修改 Hoozit 的原型对象也会修改 Gizmo 类型的对象,这不是预期的行为。
Hoozit.prototype = new Gizmo()
继承自 Gizmo,然后单独保留 Gizmo。The reason is that using
Hoozit.prototype = Gizmo.prototype
would mean that modifying Hoozit's prototype object would also modify objects of type Gizmo, which is not expected behavior.Hoozit.prototype = new Gizmo()
inherits from Gizmo, and then leaves Gizmo alone.其他答案解决了这个问题,但如果你确实想继承原型,你可以使用一些寄生魔法:
现在你可以替换:
与
它可能不值得麻烦,除非你有一个真正的大Gizmo构造函数(唯一的胜利我的建议是你不必调用 Gizmo 的构造函数来连接原型)。 我在 TDD JavaScript Examples。
The other answers address this, but if you DO want to inherit the prototype, you can use some parasitic magic:
Now you can replace the:
with
It might not be worth the trouble unless you have a real big Gizmo constructor (the only win in my suggestion is that you don't have to call Gizmo's constructor to hook up the prototype). I have examples of many of these types of patterns in TDD JavaScript Examples.
如果他写成 Hoozit.prototype = Gizmo.prototype ,那么他以后对 Hoozit 原型所做的任何修改都会反映在 Gizmo 原型中。
If he writes Hoozit.prototype = Gizmo.prototype any modfication he makes later to the prototype of Hoozit will be reflected in the prototype of Gizmo.
除了 Triptych 的回答之外:Hoozit 实例还将继承 Gizmo 的所有实例属性,而不仅仅是原型中定义的属性; 例如:
In addition to Triptych's answer: Hoozit instances will also inherit all instance properties of Gizmo, not only the ones defined in the prototype; eg: