简体   繁体   English

JavaScript ES6 类 - 调用静态方法在类中设置实例是反模式吗?

[英]JavaScript ES6 Classes - Is it an anti-pattern to call a static method to setup an instance within a class?

I'm creating a class that calls a method to do some processing and setup some data.我正在创建一个调用方法来进行一些处理和设置一些数据的类。 I'm using ESLINT and it is warning me that I shouldn't use _ in front of a method that doesn't reference this within.我正在使用 ESLINT,它警告我不应该在没有引用this的方法前面使用_ This method is only meant to be used within the instance.此方法仅用于在实例中使用。 Turning the method into a static method removes the warning.将该方法转换为静态方法会删除警告。 Was wondering if it is an anti-pattern to using static methods to setup an instance during instantiation or should it be kept as an instance method?想知道在实例化期间使用静态方法设置实例是否是一种反模式,还是应该将其保留为实例方法? Example class below.下面的示例类。 Thanks!谢谢!

class AppDataArray extends BaseXmlBuilder {
  constructor(arrayOfData) {
    super();
    this.payload = this._buildAppDataArray(arrayOfData);
  }

  static _buildAppDataArray(arrayOfData) {
    const arrayOfAppData = arrayOfData.map((data) => {
      const { app, name, value } = data;
      const appData = new AppData(app, name, value);
      return appData.payload;
    });
    return arrayOfAppData;
  }
}

It depends on your case.这取决于你的情况。 Do you want to use this method very often both inside and outside the class ?你想在课堂内外经常使用这种方法吗? It so then keeping it static is fine.所以让它保持静止就可以了。 But if you don't need this method outside class without wanting to make its object then convert it into normal member method.但是,如果您不需要在类之外使用此方法而不想使其成为对象,则将其转换为普通成员方法。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM