问题描述
我一直在观看道格拉斯·克罗克福德在YUI剧院的演讲,我有一个关于JavaScript继承的问题...
I've been watching Douglas Crockford's talks at YUI Theater, and I have a question about JavaScript inheritance...
Douglas给出了这个例子来说明Hoozit 继承自Gizmo:
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;
};
他为什么写 Hoozit.prototype = new Gizmo()
而不是 Hoozit.prototype = Gizmo.prototype
?
这两者有什么区别吗?
Is there any difference between these two?
推荐答案
原因是使用 Hoozit.prototype = Gizmo.prototype
意味着修改Hoozit的原型对象也会修改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()
继承自Gizmo,然后单独留下Gizmo。
Hoozit.prototype = new Gizmo()
inherits from Gizmo, and then leaves Gizmo alone.
这篇关于JavaScript中的原型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!