0

I know arrow functions binds the parent-scope to 'this' keyword, but is it not the same parent calling the arrow function in this two scenarios?

Both are being called by a console.log inside a "fn" function. Why do I receive different context output?

Expected:

function wuwu() {
    this.a = () => this

    this.fn = function () {
        console.log(this) // wuwu {a: ƒ, fn: ƒ}
        console.log(this.a()) // wuwu {a: ƒ, fn: ƒ}
    }
}
const wewe = new wuwu()
wewe.fn()

Not expected:

let wuwu = {
  a: () => this,
    
  fn: function() {
      let fn2 = () => {
          console.log(this) // {a: ƒ, fn: ƒ}
          console.log(this.a()) // Window {0: Window, 1: Window, window: Window, self: Window, document: document, name: '', location: Location, …}
      }
      fn2()
 }
}
wuwu.fn()
  • `fn: function() {` so it depends on the calling context - but `a: () => this,` so it depends on the `this` of the outer scope (which is the window) – CertainPerformance May 03 '22 at 01:09

0 Answers0