在 javascript 中定义类和实例的方法

问题描述 投票:0回答:0

我希望能够从实例和类中访问一个方法:

class AClass {
  // I want to make this both static and normal
  method() {
    console.log("Method called");
  }
}

我希望能够从实例访问

static
方法(就像在python中使用
@staticmethod
)但我不能,因为它给出了一个错误:

class AClass {
  static method() {
    console.log("Method called");
  }
}

AClass.method();  // this works
(new AClass).method();  // this doesn't work

类似问题

  • 从常规 ES6 类方法调用静态方法 这个问题不是那个问题的重复,因为我想要静态方法和实例方法的同名。这个问题是关于从实例方法(不同名称)调用静态方法
javascript class methods static-methods
© www.soinside.com 2019 - 2024. All rights reserved.