node.js - NodeJS : Can a static method call the constructor of the same class?

标签 node.js constructor static non-static

我有一个问题:如果我的类中有一个构造函数:

module.exports = class ClassA{
  constructor(stuffA, stuffB) {
    this.stuffA = stuffA;
    this.stuffB = stuffB;
  }

  NonStaticMethod() {
    console.log(this);
  }

  static StaticMethod(stuffA, stuffB) { 
      const element = new ClassA(stuffA, stuffB);
      console.log(element)
      element.NonStaticMethod();
    });
  }
};

因此,NonStaticMethod 会打印除 StaticMethod 之外的对象的其他信息。那么两个问题:

  1. 我可以从同一个类的静态方法调用构造函数吗?

  2. 从静态方法调用非静态方法的正确方法应该是什么?

最佳答案

以下代码打印“true”,因此在 NonStaticMethod 中 this.stuffA 正确依赖构造函数中定义的值:

class ClassA{
    constructor(stuffA, stuffB) {
        this.stuffA = stuffA;
        this.stuffB = stuffB;
    }

    NonStaticMethod() {
        console.log(this.stuffA === "a");
    }

    static StaticMethod(stuffA, stuffB) {
        const element = new ClassA(stuffA, stuffB);
        element.NonStaticMethod();
    };
}

ClassA.StaticMethod("a","b")

关于node.js - NodeJS : Can a static method call the constructor of the same class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56239456/

相关文章:

c# - 在 C# 构造函数中使用 this()

php - PHP中静态类的不同实例

c++ - 内联构造函数可以在 C++ 中使用初始化列表吗?

java - 当我们创建多个对象时,静态 block 会发生什么?

iphone - 如何在 iPhone/XCode 中定义静态字符串表?

javascript - 将socket.io封装在一个类中

node.js - 将mongodb集合数据导出到 Node js中的csv文件

javascript - Express Handlebars 自定义路径

javascript - Passport.js 模块,未定义callbackURL

c++ - 如何从 json 字符串创建工厂方法