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?
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
.
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
Both way are correct
Foo.testIt()
this will refer to Foo
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With