我有以下类(class),我无法更改
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 中是否可行,如果可以,如何实现?
最佳答案
您需要 延长 class1 到 class2 像:
class class1{
constructor(let x , let y){
this.x = x;
this.y = y;
}
}
class class2 extends class1{
// x & y just arguments for explaining
constructor(let x , let y){
// calling class1 after extends
super(x , y);
}
}
关于javascript - 我可以修补现有类以扩展另一个类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64710267/