this with arrow
- TypeScript course
- Beginner
- Lesson 48/89
- 4 min
Learn the this context in arrow functions.
Arrow and this
Arrow functions do not have their own this. this is taken from the enclosing scope (lexical binding). In regular functions, this is determined by the call site.
const nesne = {
ad: "Ali",
goster: function(): string {
const ok = (): string => this.ad; // this = nesne
return ok();
}
};
nesne.goster(); // "Ali"An arrow function inherits this from its enclosing scope.
Arrow functions in callbacks
In nested callbacks inside a method, using a regular function loses this. An arrow function preserves the method's this, so arrow functions are preferred in callbacks.
const nesne = {
ad: "Ali",
goster: function(): void {
[1].forEach(() => console.log(this.ad));
}
};An arrow function does not lose this inside a callback.
Practice Use this with an arrow function
Define an object named nesne with the ad property set to "Ali". The goster method should be a regular function containing an arrow function that returns this.ad. Print the result of calling nesne.goster() with console.log.
Starter code
// nesne adında bir nesne tanımla
// ad özelliği "Ali" olsun
// goster metodu düz fonksiyon olsun
// goster içinde ok fonksiyonu this.ad döndürsün
// nesne.goster() sonucunu yazdırSample solution
const nesne = {
ad: "Ali",
goster: function(): string {
const ok = (): string => this.ad;
return ok();
}
};
console.log(nesne.goster());Expected output
Ali
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is <code>this</code> determined in an arrow function?
- Determined by the call site
- Inherited from the enclosing scope Correct answer
- It is always the global object
- It is always undefined
Explanation: An arrow function does not create its own <code>this</code>; it takes the enclosing scope's <code>this</code> lexically. In regular functions, <code>this</code> varies by call site.
2 The this property in the arrow function
const nesne = {
ad: "Ali",
goster: function(): string {
const ok = (): string => this.____;
return ok();
}
};
const nesne = {
ad: "Ali",
goster: function(): string {
const ok = (): string => this.ad;
return ok();
}
};
Explanation: The object has the <code>ad</code> property; the arrow function returns <code>this.ad</code> via lexical <code>this</code>. <code>name</code>, <code>yas</code> and <code>id</code> are not present on the object.
3 this binding concepts
| Term | Meaning |
|---|---|
Arrow function this |
Taken from lexical scope |
Regular function this |
Determined by call site |
Lexical scope |
Enclosing scope's this |
this binding |
Lexical in arrow functions |