7

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?

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

0

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 

Comments

-1

TypeScript is a superset to verify if your code types are logically consistent (type checking), it does not verify if your code is good practice or what it does. So it will compile as this code type checking is valid.

So what does this code do?

Foo.temp means the variable in the Foo Class

this.temp means the variable in the instance of the Foo Class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.