0

I understood that the "this" keyword means the current execution context, or where the code was invoked. It may be the global object or an object that called it.

const nameObj = {
  name: "Jack",
logName: function(){
console.log(this.name)}
}
nameObj.logName() // Jack

It works fine for the regular functions, but for the arrow functions it returns the global object instead:

const nameObj = {
  name: "Jack",
logName: ()=> {
// console.log(this.name) would be undefined
console.log(this)
}
}
nameObj.logName() // The window object on the browser's console

Everything is clear till this point, however, I cannot understand when it comes to nesting an arrow function inside a regular function, the "this" keyword in the arrow function refers to the object that called it instead of the usual global or window object.

const nameObj = {
  name: "Jack",
  logName: function () {
    return () => console.log(this.name);
  },
};
const arrowLogName = nameObj.logName();
arrowLogName(); // Jack

Is the arrow function implicitly "capturing" the "this" value or something else I am missing?

ModyDz
  • 115
  • 8
  • The first bullet point in the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) and covered explicitly later on: [Arrow functions used as methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#arrow_functions_used_as_methods) – pilchard Apr 11 '22 at 20:56

0 Answers0