我可以在不使用其名称的情况下引用 class 的静态变量吗? (用于继承)
Can I refer to a static variable of a class without using its name? (for inheritance)
假设我有一些代码:
class BuildingWithRecipe {
static recipeType = ""
findRecipe(){
doStuffWith([not this].recipeType);
}
}
class Furnace extends BuildingWithRecipe {
static recipeType = "smelting"
}
我希望能够使用 class 的实例方法中的关键字访问 class 的静态方法,因此当我扩展 BuildingWithRecipe(假设使用 Furnace)时,我可以简单地设置静态 recipeType 属性 并且 findRecipe 方法在调用 Furnace.
实例时将访问 Furnace.recipeType 而不是 BuildingWithRecipe.recipeType
这可能吗?
你可以用 this.constructor
:
findRecipe(){
doStuffWith(this.constructor.recipeType);
}
假设我有一些代码:
class BuildingWithRecipe {
static recipeType = ""
findRecipe(){
doStuffWith([not this].recipeType);
}
}
class Furnace extends BuildingWithRecipe {
static recipeType = "smelting"
}
我希望能够使用 class 的实例方法中的关键字访问 class 的静态方法,因此当我扩展 BuildingWithRecipe(假设使用 Furnace)时,我可以简单地设置静态 recipeType 属性 并且 findRecipe 方法在调用 Furnace.
实例时将访问 Furnace.recipeType 而不是 BuildingWithRecipe.recipeType这可能吗?
你可以用 this.constructor
:
findRecipe(){
doStuffWith(this.constructor.recipeType);
}