如何在javascript中实例化另一个类中的类?类有静态方法和非静态方法
export default class MyClass {
static staticMethod() {
return console.log(`this is static method`);
}
nonStaticMethod() {
return console.log(`this is not static method`);
}
}我可以从上面访问一些其他js文件中的静态方法,它是这样的类:
import MyClass form "somewhere";
MyClass.staticMethod(); //this works 但是如何访问非静态方法呢?
//This does not work
import MyClass form "somewhere";
MyClass.nonStaticMethod();为了使其正常工作,需要创建/传递MyClass的实例。我怎么能做这样的事情呢?
let myClass = new MyClass();
myClass.nonStaticMethod();
//I am getting uncaught ReferenceError: nonStaticMethod is not defined发布于 2019-07-25 03:30:46
创建类的一个实例,然后调用该实例方法。你不能在这样的静态上下文中调用实例方法。参见下面的示例代码:
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
发布于 2019-07-25 03:09:06
我真的看不出有什么问题。这段代码运行得很好。
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();
https://stackoverflow.com/questions/57189647
复制相似问题