gpt4 book ai didi

JavaScript - 类在条件下扩展

转载 作者:行者123 更新时间:2023-12-01 16:05:01 26 4
gpt4 key购买 nike

事情就是这样。我有一个名为 A 的主要类(class)。
我希望这个类扩展 B 类。

class A extends B {}

但实际上,我希望 B 类在特定条件下扩展 C、D 或 E:
class B extends B1 {}

或者
class B extends B2 {}

或者
class B extends B3 {}

所以 B 类将是一个“假”类,只是为了检查一个条件然后扩展正确的类。
在决赛中,结果将与以下内容相同:
class A extends B1 {}

或者
class A extends B2 {}

或者
class A extends B3 {}

我知道这在 PHP 中是可能的,例如抽象类或包装类。
但是如何在 JavaScript ES6 中做到这一点?

谢谢

最佳答案

奇怪,但可能:

class subClassFirst {

report() {
console.log(`Extended ${this.name} from the first class`);
}
}

class subClassSecond {

report() {
console.log(`Extended ${this.name} from the second class`);
}
}

class subClassThird {

report() {
console.log(`Extended ${this.name} from the third class`);
}
}

function classCreator(condition) {
let sub;
switch (condition) {
case 'first':
sub = subClassFirst;
break;
case 'second':
sub = subClassSecond;
break;
case 'third':
sub = subClassThird;
break;
}

return (class extends sub {
constructor(name) {
super();
this.name = name;
}
});
}

let myClass;

myClass = classCreator('first');
let mcf = new myClass('f');

myClass = classCreator('second');
let mcs = new myClass('s');

myClass = classCreator('third');
let mct = new myClass('t');

mcf.report();
mcs.report();
mct.report();

关于JavaScript - 类在条件下扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com