【问题标题】:Can I refer to a static variable of a class without using its name? (for inheritance)我可以在不使用名称的情况下引用类的静态变量吗? (用于继承)
【发布时间】:2021-12-30 00:20:30
【问题描述】:

假设我有一些代码:

class BuildingWithRecipe {
    static recipeType = ""
    findRecipe(){
        doStuffWith([not this].recipeType);
    }
}

class Furnace extends BuildingWithRecipe {
    static recipeType = "smelting"
}

我希望能够使用该类的实例方法中的关键字访问该类的静态方法,因此当我扩展 BuildingWithRecipe(比如说用 Furnace)时,我可以简单地设置静态 recipeType 属性和 findRecipe当在 Furnace 实例上调用时,方法将访问 Furnace.recipeType 而不是 BuildingWithRecipe.recipeType。

这可能吗?

【问题讨论】:

  • 为什么static recipeType 需要在BuildingWithRecipe 中?
  • @adiga 我认为这只是一个例子。可能有点太简化了,因为它可以很容易地作为基类的构造函数参数来完成,并且子类调用super("smelting")

标签: javascript inheritance


【解决方案1】:

您可以使用this.constructor

findRecipe(){
    doStuffWith(this.constructor.recipeType);
}

【讨论】:

    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2012-08-11
    相关资源
    最近更新 更多