Like other programming languages such as C# and Java,TypeScript also has the this keyword.The this keyword refers to the current object.The object which this keyword refers is different depending upon the context.
Use of this keyword in TypeScript depends on the context in which it is used.
In the following example truck class uses the this keyword.The keyword refers to different objects in the constructor and the getEmployeeName function.In the constructor this refers to the Employee class whereas in the getEmployeeName ,this refers to the any type which is a special type in TypeScript.
class Employee{ name:string; constructor(name:string) { this.name = name;//type of a is Employee alert(this.name); alert(this.getEmployeeName().name); } getEmployeeName=function() { return this;//this is of any type } } let employee= new Employee("Amit"); let button = document.createElement('button'); button.textContent = "search employee"; button.onclick = function() { alert(employee.getEmployeeName()); } document.body.appendChild(button);
If you execute the above code you will get the employee name displayed two times.Both getEmployeeName () function and constructor refers to the Employee object at run time.But at compile time type of this in function is any.TypeScript any type can refer to any type in TypeScript.
Leave a Reply