Javascript function context: bind vs call & apply

In case you don't know, or you are starting with javascript, there is a method in the Function prototype called bind that, once you start, you will never stop using it. This method was added in ES5 (so if you are developing for IE < 9, I recommend to have a look at the underscore polyfill) and let the developer define what the object this will be inside the function. Here it is an example:

var f = function(){
    console.log(this.toString());
}

var bound = f.bind('bind');

bound(); // bind

On the other hand, there are two old javascript friends, call & apply Function methods, which execute the function and also can customize the context of execution, allowing to define the this object when it is given as their first argument:

var f = function(){
    console.log(this.toString());
}

f.apply('apply', []); // apply
f.call('call'); // call

So far so good, but there is a situation where the behaviour of these functions is not that clear. What would happen if the call or apply methods are used on a already bound function? Let's find out...

var f = function(){
    console.log(this.toString());
}

var a = 'apply',
    b = 'bind',
    c = 'call'
;

var bound = f.bind(b);

bound(); // bind

f.apply(a, []); // apply
f.call(c); // call

bound.apply(a, []); // bind
bound.call(c); // bind

Want to try it? here you have the bind vs call & apply jsfiddle.

Yes, bind has won! I would have bet for call & apply because they are executed after bind, but it seems like a bound function is always executed with the given this parameter. From now on, I will be careful when using call & apply, they don't always use the this object passed as argument.

© arqex 2023
Someday,
we'll find ourselves
far, far away...
Transitions here have been created using a library of mine:
React interactable.
This awesome hyperspace effect thanks to this codepen from Noah Blon.
Software development can be fun!
Javier Márquez
Software developer