0

I was reading Kyle Simpson's YDKJS about the this keyword.

There was an example illustrating how the this binding my be lost.

Here's the example

function foo() {
    console.log( this.a );
}

function doFoo(fn) {
    // `fn` is just another reference to `foo`

    fn(); // <-- call-site!
}

var obj = {
    a: 2,
    foo: foo
};

var a = "oops, global"; // `a` also property on global object

doFoo( obj.foo ); // "oops, global”

If this depends on the the callsite, if I rewrite the example in the following way

function foo() {
    console.log( this.a );
}

function doFoo(fn) {
    fn();
}

var obj = {
    a: 2,
    foo: foo
};

var obj2 = {
    a: 3,
    doFoo: doFoo
}


var a = "oops, global"; // `a` also property on global object

obj2.doFoo(obj.foo); // logs "oops, global” 

In my example the callsite is function doFn, and its context is obj2. Why is the global this still printed?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Soumik Sur
  • 115
  • 1
  • 1
  • 10
  • `doFoo( obj.foo.bind(obj) );` – adiga Jul 21 '19 at 17:21
  • I've edited the question. Hope my question is a little more clear now, what I am looking for is the why. – Soumik Sur Jul 21 '19 at 18:53
  • The accepted answer to [How does the “this” keyword work?](https://stackoverflow.com/q/3127429/215552) explains the why in great detail. If there's something you don't understand about how the answers to the duplicates answer your question, edit your question with the specific questions you have. You may want to reference the parts of the answers you're having trouble with (if any). – Heretic Monkey Jul 21 '19 at 18:57

0 Answers0