说我有一个班级:
function Foo() {
this.foo1 = null;
this.foo2 = function() { return false;};
}
Run Code Online (Sandbox Code Playgroud)
我希望其他对象从中继承变量和函数.
function Bar(){}
function Baz(){}
Run Code Online (Sandbox Code Playgroud)
然后实例化我的对象:
var bar = new Bar();
bar.foo1 // returns null
bar.foo2() // returns false
Run Code Online (Sandbox Code Playgroud)
什么是适当的功能包括 Foo在Bar和Baz?
我已经做了Bar.prototype = new Foo();但似乎在我们心爱的IE上失败了(<9).
如果将所有属性附加到原型(这是优选的,至少对于方法而言),
function Foo() {}
Foo.prototype.foo1 = null;
Foo.prototype.foo2 = function() { return false;};
Run Code Online (Sandbox Code Playgroud)
然后将父母的原型分配给孩子的原型就足够了:
function inherit(Child, Parent) {
var Tmp = function(){};
Tmp.prototype = Parent.prototype;
Child.prototype = new Tmp();
Child.prototype.constructor = Child;
}
inherit(Bar, Foo);
Run Code Online (Sandbox Code Playgroud)
这里我们使用中间构造函数来"解耦"两个原型.否则,如果你改变一个,你也会改变另一个(因为它们引用同一个对象).这种方式实际上非常受欢迎并且被几个库使用.
如果没有,你必须在子的构造函数中调用父的构造函数:
function Bar() {
Foo.call(this);
}
Run Code Online (Sandbox Code Playgroud)
这是你应该做的事情,将构造函数中设置的属性分配给当前对象.
另外一句话:
Bar.prototype = new Foo();
Run Code Online (Sandbox Code Playgroud)
这应该工作(实际上也在IE中),但它有两个主要缺陷:
所有实例属性中设置Foo将成为所有国家的共同特性Bar实例.
如果Foo期望某些参数仅在您创建Bar实例时可用,该怎么办?