Javascript和继承 [英] Javascript and Inheritance
问题描述
说我有一个 Class :
function Foo() {
this.foo1 = null;
this.foo2 = function() { return false;};
}
我希望其他对象继承变量&它的功能。
And I want other objects to inherit variables & functions from it.
function Bar(){}
function Baz(){}
然后实例化我的对象:
var bar = new Bar();
bar.foo1 // returns null
bar.foo2() // returns false
在 Bar
和<$ c $中包含 Foo
的正确功能是什么? c> Baz ?
What's the proper function to include Foo
in Bar
and Baz
?
我已经做了 Bar.prototype =新的Foo();
但它似乎在我们心爱的IE上失败了(< 9)。
I already did Bar.prototype = new Foo();
but it seems to fail on our beloved IE (<9).
推荐答案
如果将所有属性附加到原型(这是可取的,至少对于方法而言),
If you attach all the properties to the prototype (which is preferable, at least for methods),
function Foo() {}
Foo.prototype.foo1 = null;
Foo.prototype.foo2 = function() { return false;};
然后将父母的原型分配给孩子的原型就足够了:
then assigning the parent's prototype to the child's prototype is sufficient:
function inherit(Child, Parent) {
var Tmp = function(){};
Tmp.prototype = Parent.prototype;
Child.prototype = new Tmp();
Child.prototype.constructor = Child;
}
inherit(Bar, Foo);
这里我们使用中间构造函数来解耦两个原型。否则,如果你改变一个,你也会改变另一个(因为它们引用同一个对象)。这种方式实际上非常受欢迎并被几个库使用。
Here we used an intermediate constructor function to "decouple" the two prototypes. Otherwise if you'd change one, you'd change the other one too (as they reference the same object). This way is actually pretty popular and used by a couple of libraries.
如果没有,你必须在子的构造函数中调用父的构造函数:
If not, you have to call the parent's constructor function inside the child's constructor function:
function Bar() {
Foo.call(this);
}
这是你应该做的事情,分配在当前对象的构造函数。
This is something you always should do, to assign the properties set up in the constructor function to the current object.
您的另一种评论:
Bar.prototype = new Foo();
此应工作(实际上也在IE中),但它有两个主要缺陷:
this should work (also in IE actually), but it has two major flaws:
-
所有实例属性在
Foo中设置
将成为所有Bar
实例共享的属性。
All the instance properties set up in
Foo
will become properties shared by allBar
instances.
如果 Foo
期望某些参数仅在您创建 Bar
实例时可用?
What if Foo
expects some arguments that are only available when you create a Bar
instance?
这篇关于Javascript和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!