我正在尝试从模块内的另一个类扩展一个类。代码看起来是这样的:
let af = {
MyClass: class {
constructor() {
console.log("constructor of my class");
}
},
myNextClass: class extends this.MyClass { // *
constructor() {
console.log("constructor of the next class");
}
},
myOtherClass: class extends this.MyClass {
constructor() {
console.log("constructor of the other class");
}
},
}
在结果控制台中抛出TypeError:Uncaught TypeError: class heritage this.MyClass is not an object or null
指的是线*。你能帮我修一下吗?
this
仅在调用对象的方法时设置,在初始化对象时不可用。
在赋值之后才能引用变量af
,而不是在创建文字的过程中。
所以你需要把这个分开。在对象文字中定义第一个类,其余的需要赋值,以便它们可以引用变量。
let af = {
MyClass: class {
constructor() {
console.log("constructor of my class");
}
}
};
af.myNextClass = class extends af.MyClass {
constructor() {
super();
console.log("constructor of the next class");
}
};
af.myOtherClass = class extends af.MyClass {
constructor() {
super();
console.log("constructor of the other class");
}
};
new af.MyClass();
new af.myNextClass();
new af.myOtherClass();