Search code examples
javascriptfunctioncallbind

Once a function is bound with `bind`, its `this` cannot be modified anymore?


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?


Solution

  • .bind("FOO") returns a function that will have "FOO" for this

    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").