【问题标题】:NodeJS: Can a static method call the constructor of the same class?NodeJS:静态方法可以调用同一个类的构造函数吗?
【发布时间】:2019-05-21 13:31:53
【问题描述】:

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

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. 从静态方法调用非静态方法的正确方法应该是什么?

【问题讨论】:

  • 1.是的,2。你永远不会从静态调用非静态。您在实例(非静态)或类(静态)上调用方法。当您在静态方法中时,您根本不在实例中。一切都是我的,它打印了两次“ClassA ...”。你想解决什么问题?
  • 基本上,实例中存储的信息是错误的或未定义的。因此,如果我调用 this.stuffA ,它将打印与最初存储在实例中不同的信息
  • 我复制粘贴你的代码并运行它,最后有太多的糊状物 } 但没有你说的问题,看我的回答。

标签: node.js constructor static non-static


【解决方案1】:

以下代码打印“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")

【讨论】:

  • 答案是完全正确的,因为我错误地创建了实例对象。非常感谢
猜你喜欢
  • 2021-11-08
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 2011-11-07
相关资源
最近更新 更多