简体   繁体   English

创建 class 的实例以调用 static 方法

[英]Creating an instance of a class to call static methods

I recently came across some code which looks something like this,我最近遇到了一些看起来像这样的代码,

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

My question is, what is the need to do something like this?我的问题是,有什么需要做这样的事情? Why would a person create an instance like this, instead of creating an instance of the class 'the normal way'.为什么一个人会创建这样的实例,而不是创建 class '正常方式'的实例。

What is the benefit of doing thing like this?做这样的事情有什么好处?

It looks like the Singleton pattern .它看起来像Singleton 模式 This pattern is used to ensure that a class has only one instance: the constructor is private, so it cannot be used from the outside of the class.此模式用于确保 class 只有一个实例:构造函数是私有的,因此不能从 class 外部使用。

Regarding this particular implementation, I would suggest a couple of fixes:关于这个特定的实现,我建议几个修复:

  • this.instance in the static method should be MyClass.instance instead this.instance方法中的 this.instance 应该是MyClass.instance
  • in the following call new this(myString) , myString will be undefined because non static variables cannot be referenced from the static context在以下调用new this(myString)中, myStringundefined ,因为无法从 static 上下文引用非 static 变量
  • there is no way to set myString没有办法设置myString
  • public static Instance {... } should be a static method instead: public static instance() {... } public static Instance {... }应该是 static 方法: public static instance() {... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建一个javascript对象来模拟一个类和静态方法? - Creating a javascript object to emulate a class and static methods? 制作一个 class 别名来调用 static 方法 - make a class alias to call static methods 创建实例时调用class中的所有方法 - Call all methods in a class when an instance is created 无法使用静态方法返回的类实例访问类方法 - not able to access class methods using the class instance returned by a static method 从常规 ES6 类方法调用静态方法 - Call static methods from regular ES6 class methods 检测类的静态和实例方法的参数和返回值 - instrumenting arguments and return value of class's static and instance methods 从类而不是实例中获取非静态方法 - Get non-static methods from a class instead of an instance 在 JavaScript 中创建只有抽象 class 可以访问的 static 方法 - Creating static methods that only the abstract class can access in JavaScript 为什么 Object class 主要使用 static 方法,而数组 ZA2F2ED4F8EBC2CBB14C21A29DZ 主要使用实例方法? - Why is the Object class using mostly static methods while the Array class is mostly having instance methods? 无法在创建的实例上调用refresh()或任何View类方法 - Unable to call refresh() or any of View class methods on created instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM