0

I am not understanding how the this keyword is referenced when used inside or invoking certain functions. I've provided a code snippet to illustrate my misconceptions.

//I am not understanding why the following expression works:
const data = {
  name: "HOME",
  lowerCase: function(){
    return this.name.toLowerCase()
  }
}

console.log(data.lowerCase())

//but the following doesn't work when using an arrow function
const data2 = {
  name: "ABOUT",
  lowerCase: ()=>{
    return this.name.toLowerCase();
  }

}

console.log(data2.lowerCase()) // expected output / "about"


/*
*I recognize that the "this" keyword behaves differently inside an arrow function. 
*My current understanding is that when using arrow functions, "this" references the encapsulating object which I thought was data2.  
*Please help clarify my misconceptions. Thanks in advance.
*/
  • 2
    _"My current understanding is that when using arrow functions, "this" references the encapsulating object_" - It doesn't reference the surrounding object when in an arrow function, it represents the value of `this` in the surrounding scope outside of the arrow function (ie: the value of `this` directly above `const data2 = {` line). You can see the link above your question for more details – Nick Parsons Aug 12 '23 at 12:16

0 Answers0