I'm currently reading Chapter 2 of You Don't Know JS: this and Object Prototypes.
Let's say we have this code:
function foo() {
console.log(this.a);
}
var obj = {
a: 33,
foo: foo
}
var a = 22;
I understand implicit this binding:
obj.foo(); // 33
I even understand how using it as a callback function makes it "lose" it's this
value:
setTimeout(obj.foo, 1000); // undefined
What I don't understand is the following excerpt about Explicit Binding using call()
and apply()
:
Unfortunately, explicit binding alone still doesn't offer any solution to the issue mentioned previously, of a function "losing" its intended this binding, or just having it paved over by a framework, etc.
I don't get why using call()
(explicit binding) still doesn't fix this issue.
I tried using the following example to re-create how it doesn't work but it seems that setTimeout
isn't able to handle using call()
? It fires immediately instead of waiting 1000 ms.
setTimeout(foo.call(obj),1000);
I do realize that using setTimeout(foo.bind(obj),1000);
would fix this, I'm just trying to wrap my head around understanding this excerpt from the book.