Bind and Object scope

This function method attaches a specified context to a function by wrapping the function and returning the wrapper. Basically it allows us to specify a context for the function now and to run the function later using that context. This is particularly useful when it comes to event handling and timeouts where you want the code to use the context that exists at the time the code is defined rather than the context at the time the code is run. As with call and apply, bind allows us to run a function in a different context to that in which it would normally run but unlike those other two calls the bind allows the context to be supplied in advance rather than at the time of running the function.

When you run setTimeout or setInterval the default context is window and not the object running the timeout. When you run an event listener the default context is the object that triggered the event and not the object the event is attached to. By using bind we can attach the object we want to use as the context at the time of defining the code and have that used at the time the code runs.

In the following example we use bind to override the context of the function called by the setTimeout to be the context at the time the setTimeout is called. This makes the properties and methods of that object (mytime in the example) available to be accessed from within the setTimeout.

mytime = function() {
this.myproperty = 'me';

mytime.prototype.go = function() {
setTimeout( this.onesecond.bind( this ), 1000 );

mytime.prototype.onesecond = function() {

One further example of the use of bind is the following single statement that allows us to convert x.y(z) into y(x,z), in other words to call a method belonging to any object independently of that object and instead specifying the object we want it to apply to as the first parameter.

var bind =;


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow