【发布时间】:2020-11-06 07:12:53
【问题描述】:
我有以下课程,我无法更改它
class Foo {
constructor() {
console.log('foo')
}
}
我想使用一个函数对其进行修补,以便它扩展另一个类(调用 super() 作为它的构造函数的第一行)
function extendWithBar(TargetCtor) {
class Bar {
constructor() {
console.log('bar')
}
}
//... secret sauce
// Equivalent of "Foo extends Bar"
// can extend other classes too
return TargetExtendingBar
}
// FooBar is a new constructor, it doesn't need to relate to Foo
// it only needs to have the same constructor
const FooBar = extendBar(Foo)
const foobar = new FooBar()
// Output:
// "bar"
// "foo"
这在 JavaScript 中是否可行,如果可以,如何实现?
【问题讨论】:
-
你可以直接做
class Bar extends Foo并打电话给 super 吗?还是我错过了什么? -
对不起,
Bar不知道它被用来扩展什么。在这种情况下,它是Foo,但它可以是任何类 -
另外顺序很重要,我需要
Foo来扩展bar,而不是Bar来扩展Foo -
你能检查一下这是否对你有帮助吗?:stackoverflow.com/questions/38546512/…
-
不,如果
Foo还没有extend另一个类,则以后无法添加它。您需要完全覆盖Foo。
标签: javascript