Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer static variables in the same class in TypeScript?

Tags:

typescript

Consider the following code:

class Foo {

    private static temp: Number;

    public static testIt() {
        this.temp = 0;// Var 1
        Foo.temp = 0;// Var 2
    }
}

I don't get any errors from TS when I compile this class. Does it mean that both variants are possible to refer static variable?

like image 723
Pavel_K Avatar asked Oct 16 '18 12:10

Pavel_K


3 Answers

Yes, although I wouldn't use the first.

The reason the first one works is because this in a function is set to whatever came before the dot operator. That is

Foo.testIt()
^^^ <- this will be Foo

This roundabout way is confusing in a sense that you expect this to be an instance, but there's no instance here.


In conclusion, the two are almost always equivalent, but I would still use Foo over this.

like image 193
Madara's Ghost Avatar answered Sep 30 '22 21:09

Madara's Ghost


Yes, both versions refer to the static field inside a static method. Inside a static method this refers to the current object the method is being invoked on which will be the class.

Be careful though if you assign the static method to a different variable, this will no longer refer to the class (since the method will not be invoked on the class). The class named access will work regardless of how the method is called.

class Foo {

    private static temp: Number = 1;

    public static testIt() {
        console.log(this.temp)
        console.log(Foo.temp)
    }
}

Foo.testIt(); // Outputs 1, 1 

let m = Foo.testIt;
m(); // Outputs undefined, 1 
like image 38
Titian Cernicova-Dragomir Avatar answered Sep 30 '22 20:09

Titian Cernicova-Dragomir


Both way are correct

  • when you run Foo.testIt() this will refer to Foo
  • Foo.temp will look on current to global scope for variable named Foo (lexical scope) and try to update his property temp to zero

this way this point to another object rather than Foo

Foo.testIt.call({}); => undefined , zero 
like image 34
Muhammed Albarmavi Avatar answered Sep 30 '22 21:09

Muhammed Albarmavi