Arrow function this keyword

i have read that the this keyword for arrow functions is defined by the parent scope - but how do I know what the parent scope is? random examples below

for example

let dog = {
    bark: "yes",
    woof: () => { console.log(this.bark)

}
let dog = {
bark : "yes",
  test() {
    setTimeout(() => {
      console.log(`${this.bark}`);   
    }, 2000);  
  } 
}}

function test () {

let dog = {
   bark: "yes",
    woof: () => { console.log(this.bark)

}}

Once you have fixed the syntax errors in your code:

  • In the first example, woof's parent scope is the global scope (because an object does not create a new scope), so calling dog.woof() will print undefined because the global object does not have a bark property.

  • In the second example, because functions create new scopes, the anonymous arrow function’s scope is that created by the function test, so calling dog.test() will have test referring to dog as its this which is then passed down to the arrow function, and print “yes”.

    (The reason why setTimeout doesn’t interfere with the arrow function’s this is because the arrow function, when created, had it’s this set to test's this, so later when setTimeout cause the arrow function to be called from the global scope, the arrow function still refers to test's this.)

  • In the third example, test creates a new scope but because dog is declared within test i.e. the created scope, neither dog nor woof can be accessed from the global scope. You can however call woof from within test, where woof will have the same this as test, so if the object calling test does not have a bark property, woof will again print undefined.

2 Likes

thankyou alot , this was very very helpful and thanks for the bit on the setTimeout because that was the most tricky part to understand

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.