如何在javascript中的另一个class中实例化class?

How to instantiate class in another class in javascript?

如何在javascript中的另一个class中实例化class? A class 有静态和非静态方法

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

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

}

我可以在其他一些 class 的 js 文件中从上面访问静态方法,如下所示:

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

但是如何访问非静态方法?

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

为了使其正常工作,MyClass 的实例需要 created/passed。我怎样才能做这样的事情?

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

我真的看不出有什么不妥。此代码工作正常。

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

创建class的实例,然后调用实例方法。您不能像那样从静态上下文调用实例方法。请参阅下面的示例代码:

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