This is an alternative, and more typical, way to write the type definition for a method. Notice the =>
part has disappeared: it looks a lot more like a normal property type, but with the parameters part before the colon.
this
Suppose we want to change the logMessage
method to logName
and have it include the name
property of the object in the logged message. One way to do this would be to refer to person.name
in the method. This would work, but the method would be tied to the specific person
variable the object is stored in. Objects can be assigned to different variables, passed as function parameters, and so on. So we actually want a way to say "the name
property of the object the method was called on".
TypeScript provides the this
keyword to do that. It refers to the object the method was called on. The example below demonstrates a logName
method using this
.
let person = {
name: "Joe",
logName()
{
console.log(`The person's name is ${this.name}`);
}
};
// Logs "The person's name is Joe"
person.logName();
In other words, calling obj.method()
will call the function method()
with this
referring to obj
.
Now we have a way to create objects with both data properties and methods that use those data properties. This is referred to as Object Oriented Programming, or OOP.
What if you write a normal function (not a method) that uses this
? TypeScript will report this as an error, as it doesn't know what type of object this
should refer to.
function logThis()
{
// Error
console.log(`'this' is ${this}`);
}
You are allowed to write code using this
outside of a function. However in this case it just has the value undefined
. It is meant to refer to an object inside a method, so there isn't anything for it to refer to.
console.log(this); // undefined