简体   繁体   English

我可以在不使用名称的情况下引用 class 的 static 变量吗? (用于继承)

[英]Can I refer to a static variable of a class without using its name? (for inheritance)

Let's say I have some code:假设我有一些代码:

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

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

I want to be able to access a static method of a class with a keyword inside of an instance method of that class, so when I extend BuildingWithRecipe(lets say with Furnace) I can simply set the static recipeType property and the findRecipe method will access Furnace.recipeType instead of BuildingWithRecipe.recipeType when called on an instance of Furnace. I want to be able to access a static method of a class with a keyword inside of an instance method of that class, so when I extend BuildingWithRecipe(lets say with Furnace) I can simply set the static recipeType property and the findRecipe method will access在 Furnace 实例上调用时,Furnace.recipeType 而不是 BuildingWithRecipe.recipeType。

Is this possible?这可能吗?

You can do that with this.constructor :你可以用this.constructor做到这一点:

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

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

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