2 回答
TA贡献1788条经验 获得超4个赞
创建类的实例,然后调用实例方法。您不能像那样从静态上下文中调用实例方法。请参阅下面的示例代码:
class ClassA {
static staticMethod() {
return 'this is static method';
}
nonStaticMethod() {
return 'this is not static method';
}
}
//Call static method:
console.log(ClassA.staticMethod()); //Works as expected
//ClassA.nonStaticMethod(); // Uncomment and see it Will cause a Uncaught TypeError
//Call instance method:
const instance = new ClassA();
//console.log(instance.staticMethod()); // Uncomment and see it Will cause a Uncaught TypeError
console.log(instance.nonStaticMethod()); //Works as expected
TA贡献1865条经验 获得超7个赞
我真的没有看到这里有什么问题。这段代码工作得很好。
class myClass {
static staticMethod() {
return console.log(`this is static method`);
}
nonStaticMethod() {
return console.log(`this is not static method`);
}
}
myClass.staticMethod();
let classInstance = new myClass();
classInstance.nonStaticMethod();
添加回答
举报