我有以下课程,我无法更改它
class Foo {
constructor() {
console.log('foo')
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用一个函数来修补它,以便它扩展另一个类(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"
Run Code Online (Sandbox Code Playgroud)
这在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
210 次 |
| 最近记录: |