Like JavaScript, TypeScript requires the this
context to establish "where" to locate functions and properties on objects. Without it, everything would be global (more accurately, it would search the scope chain for the requested variable declaration). And, in TypeScript, the compiler would catch instances where an attempt to use a global variable is made, but not defined.
Unlike some other languages, like C#, there is no default context available within instance methods of a class (an implicit this
determined by usage). You need to be explicit and use this
when you want to refer to instance methods and properties.
If name
works without using this.name
, it would imply that there is a global name
defined elsewhere, outside of the context of the functions defined on your class. For example it could be like this:
var name: string="global";
class Test {
name: string;
public helloName():string {
return "hello " + name;
}
}
var t = new Test();
t.name = "instance";
var result = t.helloName(); // result = "hello global"
And if the function body was modified to refer to this.name
:
return "hello " + this.name;
The output would be:
var result = t.helloName(); // result = "hello instance"