在其静态方法中访问 class

Access a class inside its static methods

我正在构建一个简单的 class。我的问题是:

如何在静态 class 方法中访问 class 方法或 this

当尝试在 static 方法中访问 this 时:

const { ProductsCollection } = require('../utils/Collection')
let modeledCollection = ProductsCollection.mapToModel(legacy)

我收到 TypeErrorthis.generateModel is not a function。这是我的 class:

class ProductsCollection {
    generateModel () {
        let model = { name: 'testing' }
        return model
    }

    static mapToModel (legacy) {
        if (!isObject(legacy))
            return legacy

        let current = this.generateModel() // Here!!!
        for (let key in legacy) {
          // some code...
        }
        return current
    }
}

module.exports = { ProductsCollection }

提前致谢!

How to access a class method, or this for that matter, inside a static class method?

static 方法访问实例信息的唯一方法是创建一个实例(或接收一个实例作为参数,或关闭一个实例 [这会很奇怪],等等;例如,你需要一个实例)。这就是 static 方法的要点:它们不与 class 的实例相关联,它们与构造函数相关联。

如图所示,您的 generateModel 方法也不使用该实例,因此它也可以是 static 。然后你可以通过 this.generateModel 访问它(假设 mapToModel 是通过 ProductsCollection.mapToModel 调用的)或 ProductsCollection.generateModel (如果你不想做那个假设):

class ProductsCollection {
  static generateModel() {
    return {name: "testing"};
  }
  
  static mapToModel(legacy) {
    return this.generateModel();
    // or `return ProductsCollection.generateModel();` if you want to use
    // `ProductsCollection` specifically and not be friendly
    // to subclasses
  }
}
console.log(ProductsCollection.mapToModel({}));

或者如果generateModel需要实例信息,您可以在mapToModel中使用new ProductsCollection(或new this)创建一个实例,然后访问generateModel 在那个实例上。

class ProductsCollection {
  generateModel() {
    return {name: "testing"};
  }
  
  static mapToModel(legacy) {
    const instance = new this();
    // or `const instance = new ProductsCollection();` if you want
    // to use `ProductsCollection` specifically and not be friendly
    // to subclasses
    return instance.generateModel();
  }
}
console.log(ProductsCollection.mapToModel({}));

您不能访问实例方法,因为它是静态方法。这是一个 classic 错误。您可以在静态方法中使用实例方法的唯一方法是,如果您有可用的 class 实例(因此名称为 "instance method")。

通常你在决定什么应该是静态的什么不是静态的时犯了一些错误......我没有多想我可以建议将 generateModel 方法设为静态。另一种方法是完全删除 generateModel 方法并将其行为合并到构造函数中。这实际上取决于您的需求。

请记住,如果您在方法中访问非静态 属性,那么它可能不应该是静态的。