Just playing around with JS a bit, I'm wondering why the following code outputs "foo"
instead of "bar"
:
String.prototype.toLowerCase.bind("FOO").call("BAR")
In my understanding, .bind("FOO")
returns a function that will have "FOO"
for this
, so calling .bind("FOO")()
outputs "foo"
.
But then, .call("BAR")
calls the function with "BAR"
for this
, so "bar"
should have been outputted.
Where am I wrong?
.bind("FOO")
returns a function that will have"FOO"
forthis
Not quite. It returns a function which binds "FOO"
for this
of toLowerCase
. It works like this:
function bind(func, thisArg) {
return function () {
return func.call(thisArg);
}
}
You can rebind the this
of the returned function all you want, the call
to func
(here: toLowerCase
) is already "hardcoded" to be thisArg
(here: "FOO"
).