【问题标题】:Creating an instance of a class to call static methods创建类的实例以调用静态方法
【发布时间】:2020-04-22 04:29:40
【问题描述】:

我最近遇到了一些看起来像这样的代码,

class MyClass {
  private static instance: MyClass;
  private myString: string;

  public static Instance(myString) {
    if (!this.instance) {
      this.instance = new this(myString);
    }
    return this.instance;
  }
  private constructor(myString: string) {
    this.myString = myString;
  }
  public getMyString() {
    console.log(this.myString);
  }
}

我的问题是,有什么需要做这样的事情?为什么一个人会创建这样的实例,而不是“正常方式”创建类的实例。

这样做有什么好处?

【问题讨论】:

标签: javascript typescript class static instance


【解决方案1】:

看起来像Singleton pattern。此模式用于确保一个类只有一个实例:构造函数是私有的,因此不能从类外部使用。

关于这个特定的实现,我建议几个修复:

  • 静态方法中的this.instance 应改为MyClass.instance
  • 在下面的调用new this(myString) 中,myString 将是undefined,因为不能从静态上下文中引用非静态变量
  • 没有办法设置myString
  • public static Instance { ... } 应该是静态方法:public static instance() { ... }

【讨论】:

  • Instance 也应该是一个函数
猜你喜欢
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 2012-12-19
相关资源
最近更新 更多