Nov 11, 2013

Javascript Function call() and apply() explained



First of all 
every function in JavaScript is an object
which has some methods attached to it some are toString(), call(), and apply().
Read this article if you wonder what the difference is between a function and a method.

Every JavaScript object has a toString() method, for example, and we can use the toString() method on a function object to see its source code:
function foo()
{
    alert('x');
}

alert(foo.toString());


Because functions are objects they can have their own properties and methods, and we can treat them like data. "Functions as data" is important to remember for the next post, too, but for now we'll focus on two of a function's methods: apply(), and its counterpart: call().
Let's start with the following code:
var x = 10;

function f()
{
    alert(this.x);
}

f();

Here we have a global function by the name of f(). f() uses the this keyword to reference x, but notice we don't invoke the function through an instance of an object. So what object does this reference? this will reference the global object. The global object is where we defined the variable x. The above code does work and will show the value 10 in a dialog.

Both call() and apply() are methods we can use to assign the this pointer for the duration of a method invocation. As an example, here is how we could use the call() method:
var x = 10;
var o = { x: 15 };

function f()
{
    alert(this.x);
}

f();
f.call(o);

The first invocation of f() will display the value of 10, because this references the global object. The second invocation (via the call method) however, will display the value 15. 15 is the value of the x property inside object o. The call() method invokes the function and uses its first parameter as the this pointer inside the body of the function. In other words - we've told the runtime what object to reference as this while executing inside of function f().

Fiddling with the this pointer might sound funny, even perverse, to C++, Java, and C# programmers. What's next? Dogs sleeping with cats? Working nVidia drivers for Windows Vista? It's all part of the fun that is ECMAScript.
We can also pass arguments to the target function via call():
var x = 10;
var o = { x: 15 };
function f(message)
{
    alert(message);
    alert(this.x);
}

f("invoking f");
f.call(o, "invoking f via call");

The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method.



f("invoking f");
f.apply(o, ["invoking f through apply"]);

The apply() method is useful because we can build a function like createDelegate (from the last post) that doesn't care about the signature of the target method. The function can use apply() to pass all additional arguments to the target method via an array. 
var o = { x: 15 };

function f1(message1)
{
    alert(message1 + this.x);
}

function f2(message1, message2)
{
    alert(message1 + (this.x * this.x) + message2);
}

function g(object, func, args)
{
    func.apply(object, args);
}

g(o, f1, ["the value of x = "]);
g(o, f2, ["the value of x squared = ", ". Wow!"]);

The problem here is the awkward syntax. We are forcing the caller to stuff arguments into an array just so we call apply(). Fortunately, there is a way to make the syntax easier, but we have to introduce one more topic: the arguments identifier.

In JavaScript, every function essentially has a variable length argument list. The means we can pass 5 parameters to a function even if the function only uses one argument. The following runs without error and displays "H":
function f(message)
{
    alert(message);
}

f("H", "e", "l", "l", "o");

If we did want to access the other arguments from inside f(), we can use the arguments keyword. arguments references an Arguments object, which has a length property and feels like an array.

function f(message)
{
    // message param is the same as arguments[0]    
   
    for(var i = 1; i < arguments.length; i++)
    {
        message += arguments[i];
    }
    
    alert(message); 
}

// this will say "Hello"
f("H", "e", "l", "l", "o");

Just so you know, arguments is technically not an array, even if it walks and talks like one. arguments has a length property but no split, push, or pop methods. What we can do with arguments inside our previous g() function is copy the incoming arguments after arguments[1] into an array object that we pass to apply.

var o = { x: 15 };

function f(message1, message2)
{
    alert(message1 + (this.x * this.x) + message2);
}

function g(object, func)
{           
    // arguments[0] == object
    // arguments[1] == func
    
    
    var args = []; // empty array
    // copy all other arguments we want to "pass through" 
    for(var i = 2; i < arguments.length; i++)
    {
        args.push(arguments[i]);
    }

    func.apply(object, args);
}

g(o, f, "The value of x squared = ", ". Wow!");

When we invoke g(), we can pass additional arguments as parameters instead of stuffing the arguments into an array.

At this point, we have the theoretical knowledge needed to understand call and apply, but perhaps you are already asking a question: what if I don't want to immediately invoke the target function f()? What if I just want to arrange all the players in this little drama so that I can invoke f() at some later point (as an event handler, for example), but still have this referencing the desired object.


Using call to invoke an anonymous function

In this purely constructed example, we create anonymous function and use call to invoke it on every object in an array. The main purpose of the anonymous function here is to add a print function to every object, which is able to print the right index of the object in the array. Passing the object as this value was not strictly necessary, but is done for explanatory purpose.
var animals = [ {species: 'Lion', name: 'King'},
{species: 'Whale', name: 'Fail'} ];

for (var i = 0; i < animals.length; i++)
{
(function (i) {
this.print = function ()
  {
    console.log('#' + i + ' ' + this.species + ': ' + this.name);
  }
 this.print();
}).call(animals[i], i); }


Hope this will help you understand, Feel free to ask anything

No comments:

Post a Comment