1

I have two objects

var dog1 = {
    sound: "bark1!",
    bark: () => {
        console.log(this)
        console.log(this.sound);
    }
}

and

var dog2 = {
    sound: "bark2!",
    bark: function() {
        console.log(this);
        console.log(this.sound);
        dog1.bark();
    }
}

Now I know that if I call dog1.bark() I'll have the value of this to be equal to Window object since the value of this for an arrow function is dependent on the lexical scoping.

But if I call dog2.bark() and from within it when dog1.bark() is called, shouldn't the value of this be dog2? Since the lexical scope of the arrow function is the bark function of dog2? Or am I missing something here?

Would appreciate some clarification on this. I noticed this question got marked duplicate of this but I couldnt understand why calling an object from an old-style function still results in the value of this being equal to window

Sanchit Kapoor
  • 373
  • 1
  • 2
  • 9
  • 2
    *"But if I call dog2.bark() and from within it when dog1.bark() is called, shouldn't the value of this be dog2?"* No, for the same reason it's not `dog1` in `dog1.bark()`. The arrow function closes over the `this` where it was **created**, not the `this` where it was called. See the linked question's answers for details. – T.J. Crowder Mar 31 '19 at 15:22
  • I understand, well thanks, I guess that clears things up a bit – Sanchit Kapoor Mar 31 '19 at 15:28
  • Think of it this way: It literally does *close over* `this`, exactly like closing over any in-scope identifier. So if you had `var foo = 42; var obj = {m: () => { console.log(foo); } }; function wrapper() { var foo = 67; obj.m(); } wrapper();` Which `foo` does `obj.m` see? Right! The one with 42. Exactly the same thing (literally exactly) with `this`. – T.J. Crowder Mar 31 '19 at 16:58

0 Answers0