假设我有以下对象函数:
function A(options){
...
}
然后我想创建一个继承 A 原型(prototype)的新函数 (B)。 这些是我正在寻找的条件:
- 如果 B 的原型(prototype)被修改,则不应修改 A 的
- 当作为构造函数调用B函数时,应使用相应的选项调用A的构造函数。
B 应该是这样的:
function B(aOptions, bOptions){ ... }
var b = new B({}, {})
最佳答案
只需用this
调用A
构造函数即可
function B(aOptions, bOptions) {
A.call(this, aOptions);
// do stuff with bOptions here...
}
现在开始设置原型(prototype)
B.prototype = Object.create(A.prototype, {
constructor: {
value: B
}
});
现在 B 将拥有来自 A 的原型(prototype)方法。
添加到 B 原型(prototype)的任何新方法将不可用于 A 原型(prototype)
还有一些其他调整也可以让您的生活更轻松。
function A(options) {
// make `new` optional
if (!(this instanceof A)) {
return new A(options);
}
// do stuff with options here...
}
对B做同样的事情
function B(aOptions, bOptions) {
// make `new` optional
if (!(this instanceof B)) {
return new B(aOptions, bOptions);
}
// call parent constructor
A.call(this, aOptions);
// do stuff with bOptions here...
}
现在您可以调用 A(options)
或 new A(options)
来获得相同的结果。
与 B 相同,B(aOptions, bOptions)
或 new B(aOptions, bOptions)
将得到相同的结果。
关于javascript - 如何在javascript中扩展现有的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26303766/