Javascript function context: bind vs call & apply

March 29, 2014 10:53 am 1 comment

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:

On the other hand, there are two old javascript friends, callapply 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:

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…

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.


Let’s push your website a bit further

My name is Javier Márquez and I have more than 10 years of web programming and web designing experience. If you have a difficult development to complete, maybe you can stop by and see what I can do for you. You can find me on and Twitter.

1 Comment - Leave yours

  • transGLUKator

    .bind() creates a wrapper function, that doesn’t have “this” inside its body. So and bound.apply(a, []) don’t have context to work with. It is like calling these functions with null as first parameter.

Leave a reply

contact meAnything related to web development like javascript and CSS to create responsive designs, or PHP and node.js to make your website work properly, is my pleasure. If you have an interesting project in mind, I can help to make it real.