Specify the context of JavaScript's "this" with call, apply, and bind

One of the most ubiquitous and also confusing keywords in current JavaScript practice is "this." As you may know, "this" refers to the object performing executíon in the current context. Unfortunately, this can cause confusion and be difficult to control, as (just as in an English sentence), "this" may be vague, or it may refer to one thing when you really need it to refer to another.

Fortunately, JavaScript has a solution for this. Instead of calling functions containing "this" the normal way (e.g., by name followed by parentheses), just call the function's built-in "call" or "apply" methods (i.e., built-in in the sense that all functions inherit them from Function.prototype). This allows you to specify what you want "this" to refer to. That not only helps make clear what "this" is, but also allows you to force "this" to signify any particular object that you like.

The first argument of "call" and "apply" is the object you want "this" to be. The remaining arguments of "call" are simply your function's parameters (in order). The "apply" method has just two arguments, where the second one is an array specifying your function's parameters. This gives "apply" an advantage in that if you add more parameters to your function, you don't need to necessarily change all the calls made with "apply." The following are two equivalent examples:

myFunction.call(myObject, argument1, argument2);
myFunction.apply(myObject, [argument1, argument2]);

A third way to specify the meaning of "this" is to use the built-in "bind" method, which has syntax similar to "call" but returns a new function instead of immediately executing your function. Use "bind" when you want to prepare a version of your function (bound to a specific object) for later use (e.g., like putting it in the fridge instead of eating it right away). For example, the following codé creates a new function and then uses it to perform the same actions as the codé above:

var myBoundFunction = myFunction.bind(myObject, argument1, argument2);
myBoundFunction();

Note that unlike "call" and "apply," the "bind" method is new as of ECMAScript 5. Hence, you can't use it in IE8, Chrome 6, or other earlier browser versions unless you employ a polyfill.

No comments: