bind

bind(thisObj[, arg...]) -> Function

Wraps the function in another, locking its execution scope to an object specified by thisObj.

As discussed on the general Function page, binding can be a pretty tricky thing for a newcomer, but it generally is a very simple concept. It requires the basic understanding of the JavaScript language.

In JavaScript, functions are executed in a specific context (often referred to as “scope”). Inside the function the this keyword becomes a reference to that scope. Since every function is in fact a property of some object—global functions are properties of the window object—the execution scope is the object from which the function was called, or (more precisely) the object that holds a reference to the function:


window.name = "the window object"

function scopeTest() {
  return this.name
}

// calling the function in global scope:
scopeTest()
// -> "the window object"

var foo = {
  name: "the foo object!",
  otherScopeTest: function() { return this.name }
}

foo.otherScopeTest()
// -> "the foo object!"

Because of the dynamic nature of the language, we can’t be sure that, for instance, otherScopeTest() will always be called on our foo object. The reference to it can be copied somewhere else, like on the window object:


// ... continuing from the last example

// note that we aren't calling the function, we're simply referencing it
window.test = foo.otherScopeTest
// now we are actually calling it:
test()
// -> "the window object"

The last call demonstrates how the same function can behave differently depending on its execution scope.

When you begin passing around function references in your code, you often want them to become fixated on a specific scope. Prototype can guarantee that your function will execute with the object you want under the this keyword just by invoking bind on it. You can also save the returned function and use it multiple times if you need so.

Examples

The code below is simply proof-of-concept:


var obj = {
  name: 'A nice demo',
  fx: function() {
    alert(this.name);
  }
};

window.name = 'I am such a beautiful window!';

function runFx(f) {
  f();
}

var fx2 = obj.fx.bind(obj);

runFx(obj.fx);
runFx(fx2);

Now, what few people realize is, bind can also be used to prepend arguments to the final argument list:


var obj = {
  name: 'A nice demo',
  fx: function() {
    alert(this.name + '\n' + $A(arguments).join(', '));
  }
};

var fx2 = obj.fx.bind(obj, 1, 2, 3);
fx2(4, 5); // Alerts the proper name, then "1, 2, 3, 4, 5"

Not yet clear enough?

OK, try Justin’s sweet article explaining function binding.