由于 JS 不允许扩展多个类,因此我们可以使用像这样的复杂继承链
class Level1 {
constructor() {
this.level = 1;
}
method1() {
console.log('This is method 1');
}
}
class Level2 extends Level1 {
constructor() {
super();
this.level = 2;
}
method2() {
console.log('This is method 2');
}
}
class Level3 extends Level2 {
constructor() {
super();
this.level = 3;
}
method3() {
console.log('This is method 3');
}
}
class Level4 extends Level3 {
constructor() {
super();
this.level = 4;
}
method4() {
console.log('This is method 4');
}
}
class Level5 extends Level4 {
constructor() {
super();
this.level = 5;
}
method5() {
console.log('This is method 5');
}
}
let obj = new Level5();
obj.method1(); // Outputs: This is method 1
obj.method2(); // Outputs: This is method 2
obj.method3(); // Outputs: This is method 3
obj.method4(); // Outputs: This is method 4
obj.method5(); // Outputs: This is method 5
是的,是的,我知道,你可以将所有这些放在一个班级中,但让其保持简单。
创建一个具有除
Level1
类以外的所有方法的对象的最佳方法是什么?
我是否必须创建另一个像
Level2WithouLevel1 -> Level3WithLevel2WithouLeve1...
这样的链?
正如评论中提到的,您不能从链中删除 Level1,因为子类可能依赖于它。我们也不能直接调用类构造函数。但是您可以轻松地将类方法复制到另一个类原型中(混合),请注意,不支持这种方式(在代码片段中)。
super
调用它。
new Function
基于类列表(Level1.toString()等)的全新类层次结构
eval()