我在不同的文件中有以下代码,如代码片段中提到的:
class Human{
gender;
ethinicity;
constructor(){
this.gender = "male";
this.ethinicity = "asian";
}
async someInstanceMethod(){
// some heavy logic
}
}
// student.js file
export class Student extends Human{
age;
name;
constructor(){
super();
this.age = 10; // some default age
this.name = "John doe"; // some default name
}
// overridden method
async someInstanceMethod(){
someFalsyCondition ? doSomethingElse() : super.someInstanceMethod();
}
doSomethingElse(){
// some logic
}
}
// someOtherFile.js
let Student;
let studentInstance;
if(someCondition){
import('./student')
.then(cls => {
Student = cls.default;
studentInstance = new Student();
studentInstance.someInstanceMethod();
}).catch(e => console.error("something went wrong while initialising class", e));
}
当我这样做时
studentInstance.someInstanceMethod();
我得到super
作为undefined
。
这里出了什么问题?我如何在这里访问父类方法?
此错误与异步方法有什么关系吗?还是与动态导入有关?
(注意:这只是一个说明性示例,实际问题是有一个包含更复杂代码的 React 项目。)
你忘了
default
:export default class Student extends Human
。