简而言之
var BaseClass = function (bar) {
this.foo = bar;
};
BaseClass.prototype.doSomething = function () {
console.log("from base class");
};
var DerivedClass = function () {
BaseClass.apply(this, arguments);
};
DerivedClass.prototype = Object.create(BaseClass.prototype);
DerivedClass.prototype.doSomething = function () {
BaseClass.prototype.doSomething.call(this);
console.log("from derived class");
};
var cls1 = new DerivedClass('I am cls1');
cls1.doSomething();
console.log(cls1.foo);
更新
感谢@HMR的评论(请参见他下面的评论,非常有用),我更新了我的答案:
- “在设置
DerivedClass
的原型时,不应创建BaseClass
的新实例,而应使用Object.create
(如果需要,请进行polyfill)”
- “您还忘记初始化
BaseClass
并通过BaseClass.apply(this,arguments)
拥有它的实例变量所有权”
1/ 使用Object.create
var BaseClass = function () {
this.foo = 'bar';
};
BaseClass.prototype.doSomething = function () {
console.log("base class");
};
var DerivedClass = function () {
};
DerivedClass.prototype = Object.create(BaseClass.prototype);
注:
Object.create
"复制" Base
的原型到 Derived
中。
- 公共属性
this.foo
没有被复制到 Derived
中(因为它不是原型的一部分)- 请参见下面的第二点。
关于 Object.create
的更多信息 在这里。
2/ BaseClass.apply(this, arguments)
如上所述,this.foo
在 Derived
实例中不可用。为了使其可用,我们需要将 Base
构造函数应用到 Derived
构造函数中。
因此,Base
的所有 特权 属性(this.foo
,...)都被应用于新的 Derived
实例。
var DerivedClass = function () {
BaseClass.apply(this, arguments);
};
DerivedClass.prototype = Object.create(BaseClass.prototype);
在流行的HMR的回答中了解更多关于JavaScript继承的细节。
我将原始答案保留以供比较和教育目的。
您的方法存在问题(虽然它可能按预期工作),即
doSomething
方法被复制到每个
BaseClass
实例中(因为它声明为简单的
public
属性)。
为了避免这种情况,从而在所有
BaseClass
实例之间共享
doSomething
方法,您应该将其添加到
BaseClass
的
prototype中。
var BaseClass = function () {
};
BaseClass.prototype.doSomething = function () {
console.log("base class");
};
你无法在最终结果中看到任何区别,但是这样做可以使
doSomething
方法被“继承”,而不是被复制。
现在知道了这一点,要在Javascript中实现
原型继承:
var DerivedClass1 = function () {
};
DerivedClass1.prototype = new BaseClass();
var cls1 = new DerivedClass1();
cls1.doSomething();
var DerivedClass2 = function () {
};
DerivedClass2.prototype = new BaseClass();
DerivedClass2.prototype.doSomething = function () {
console.log("derived class (2)");
};
var cls2 = new DerivedClass1();
cls2.doSomething();
如果你想从DerivedClass
中调用parent
方法,可以使用以下方法:
var DerivedClass3 = function () {
};
DerivedClass3.prototype = new BaseClass();
DerivedClass3.prototype.doSomething = function () {
BaseClass.prototype.doSomething.call(this);
console.log("derived class (3)");
};
var cls3 = new DerivedClass1();
cls3.doSomething();
prototype
上,实例属性在构造函数上,然后你可以使用Object.create
进行继承,并像这样调用超类:BaseClass.apply(this, arguments)
。 - elclanrs