0

I'm reading "You Don't Know JS: this & Object Prototypes" and learning about the "this" keyword. I understand that "this" keyword depends on where the function is executed, or as the book refers to it as the function's call-site.

I was experimenting with some code and was looking at examples regarding "this" keyword in callbacks. In callbacks, you can identify ‘this’ by looking at how the outer function. If the outer function is defined in global scope, so its ‘this’ will point to the Window object as its invoking object. However, why does "this" still refer to the global object if the outer function is defined in the object's scope? https://thenewstack.io/mastering-javascript-callbacks-bind-apply-call/#:~:text=A%20callback%20function%20is%20a,point%20serves%20the%20code's%20purpose.

function foo() {
  console.log( this.a );
}
        
var obj = {
  a: 2,
  bar: function(fn){ 
    this.a = "in obj";
    fn();
  },
  baz: function(){ console.log(this.a); }
};
  
var a = "oops, global";
  
obj.bar(foo) // output: oops, global
obj.baz(); // outputL in obj

As you can see from the "this" keyword in the obj methods refer to the obj. But why doesn't the callback function's "this" keyword refer to the obj? The default binding rule states that "this" keyword refers to the call-site of the function. And the call-site of the foo() is bar() which belongs to the obj. I know there are possible solutions to fix this issue such as calling bind(). I'm just asking to see if I understood the concept of "this" or if I'm missing some information.

sangmin park
  • 457
  • 6
  • 12
  • `foo()` is not called off of anything, though actually it equates to `window.foo()`. `obj.baz()` is calling baz off of `obj`. So the `obj` is the `this`. – Taplar Dec 31 '20 at 20:55

0 Answers0