0

definition of this i have found online: Unlike regular functions, arrow functions do not have their own this. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

... now i guess i really didn't get the true meaning of what "going up a scope" means because i don't get why any of these examples behave the way they do. can anyone explain me why they behave the way they do?

//logs the window object
let a = {
  logThis: () =>{
    console.log(this)
  }
}


//logs the window object
let a1 = {
  logThis: () =>{
    return {
      logThis: () => {
        console.log(this)
      }
    }
  }
}

in the above example, if the value of this goes up a scope, the innermost scope is the one of the object that i want to return right? so shouldn't the first scope up (without taking into account the first arrow function) be the scope of the a1 object? with scope is it then meant only the scope of a function and the scope of object isn't taken into account?

//logs the a3 object
let a3 = {
  logThis: function(){
    return {
      logThis: () => {
        console.log(this)
      }
    }
  }
}

//logs the a4 object
let a4 = {
  logThis: () => {
    return {
      logThis: function() {
        console.log(this)
      }
    }
  }
}

finally in this example:

var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(() => {
      console.log(this.id);
    }, 1000);
  }
};

the value of this in the arrow function will be of obj. but by the definition, if the value of this in an arrow function is bound to the value of this in the closest non arrow function, isn't the closest non-arrow function the setTimeout function? so shouldn't the value of this be the window object? i know this reasoning is clearly wrong, but i don't understand why exactly.

any help would be greatly appreciated.

  • 1
    Can you please replace the code blocks with executable snippets (`<>`) with the relevant calls of `a`, `a1`, ... -> [I've been told to create a “runnable” example with “Stack Snippets”, how do I do that?](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) – Andreas Jan 04 '21 at 09:55
  • Please know that `this` is assign based on how the method is _called_, not how it's defined. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – evolutionxbox Jan 04 '21 at 09:56

0 Answers0