0

MDN: In arrow functions, this retains the value of the enclosing lexical context's this. In global code, it will be set to the global object:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

I wrote this code:

const outerObj = {
      lemon:5,
      obj:{
        egg:5,
        apple: () => {console.log(this)}
      }
    }
    
    
    
    outerObj.obj.apple()

Why global object printed? my arrow function doesn't have her own this, so she looks for her outer scope, and it should be the "this" of obj, so I expect to see { egg: 5, apple: [Function: apple] }, what I missed?

John Doe
  • 363
  • 1
  • 5
  • 17
  • 6
    Objects don't get their own `this`. Only classes and non-arrow functions do. You could instead do `console.log(outerObj);` – DemiPixel Oct 07 '21 at 18:26
  • 1
    See [How does the “this” keyword work?](/q/3127429/4642212). Objects do not create a new scope because they do not alter or create an execution context. – Sebastian Simon Oct 07 '21 at 18:32
  • The outer scope is the global scope (or the scope of the function that contains this code), there is no other scope in the code shown, given that the arrow function is the only function in the code snippet. I'm sure if you do `console.log(this)` above/below the whole code that you showed, it will also be the global object. If you wanted `this` to be `obj`, you'd have to use a _regular_ function, not an array function, so it can get its own `this` (which would be `obj` in case of the way you call it, which is as `obj.apple()`). – CherryDT Oct 07 '21 at 18:34

0 Answers0