Home > Mobile >  Can I refer to a static variable of a class without using its name? (for inheritance)
Can I refer to a static variable of a class without using its name? (for inheritance)

Time:11-22

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.

Is this possible?

CodePudding user response:

You can do that with this.constructor:

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