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?