简体   繁体   中英

How to instantiate class in another class in javascript?

How to instantiate class in another class in javascript? A class has static and non static method

export default class MyClass {
    static staticMethod() {
        return console.log(`this is static method`);
    }

    nonStaticMethod() {
        return console.log(`this is not static method`);
    }

}

I can access static method from above in some other js file which is class like this:

import MyClass form "somewhere";
MyClass.staticMethod(); //this works 

But how can I access non static method?

//This does not work
import MyClass form "somewhere";
MyClass.nonStaticMethod();

In order for this to work, instance of MyClass needs to be created/passed. How can I do something like this?

let myClass = new MyClass();
myClass.nonStaticMethod();
//I am getting uncaught ReferenceError: nonStaticMethod is not defined

I don't really see anything wrong here. This code works just fine.

 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(); 

Create an instance of the class, then call the instance method. You cant call an instance method from a static context like that. See the sample code below:

 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM