bind :: Function

bind(thisObj[, arg...]) -> Function Provides a guaranteed-binding equivalent of the original function, possibly with pre-filled arguments.

As discussed on the general Function page, binding can be a pretty tricky thing sometimes.

Prototype can guarantee that your function will execute with the object you want under the this reference, just by invoking bind on it (you are welcome to cache the returned function and use it as many times as you need).

Examples

This is basic usage, just guaranteeing the reference:

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"

Prototype API 1.5.0 - prototypejs.org