Friday, August 29, 2014

Javascript Apply

In Javascript, everything is an object. So, unlike Java and C++, Javascript functions are also objects which come with some built-in methods that you can call. One of the methods is apply which lets you call the function and explicitly pass the value of the "this" parameter as well as the arguments to the function as an array.

To refresh memories, every function call in Javascript includes a hidden argument called "this". So even when you call any regular function, it will receive a "this" as a hidden argument. If the function being called is a member of an object such as a function in an object literal then the "this" points to the object. An object literal is made up of name-value pairs, like the following:

var O = {
myData : "Seattle Seahawks",
test : function() {
// this got passed into the function as a hidden argument and points to the object "O"
console.log(this.myData);
}
}

O.test(); // Javascript interpreter will set "this" to point to the "O" object

Let's write a regular function:

function x() {
console.log("hello Lake Washington");
}

x(); // JS will pass a hidden "this" parameter, it will set it the global object which is: window object

In both of these function calls, O.test() and x(), the interpreter is deciding how to set the "this" parameter. Back to apply. Using apply, you can take control and set "this" whatever you want it to be. The method apply() takes two parameters. The first parameter is going to be the "this" value that the function receives, second parameter is an array where the elements of the array will become the regular parameters to the function. By "regular", I just mean non-hidden parameters.

oldConsoleLog.apply(this, arguments);

Let's assume arguments is a five element array. What apply does is takes each element and passes it as a separate argument to the called function. "arguments" is an array-like object that is automatically set in every function to contain all the parameter values that are passed to the function.

Post a Comment

Note: Only a member of this blog may post a comment.