Differences of function.apply() and function.call() in JavaScript

by Yang Yang on September 29, 2007

Function object methods function.apply() and function.call() basically do the same job, that is to invoke the function as if it was the method of a specified object so that the ‘this’ keyword within the function is treated as that object rather than the global object.

var x = 20;
function f(s)
{
alert(this.x + s);
}
f('!');

‘this’ keyword refers to global object by default, so the code above kicks out an alert of ’20!’. However, with

var x = 20;
var o = {x:40}; // o is an object with a property of x = 40
function f(s)
{
alert(this.x + s);
}
f('!');
f.call(o, '!'); // invoking function f as a method of object o, so this.x makes out to o.x = 40 thus an alert of '40!' instead of '20!'.
f.apply(o, ['!']); // does the same thing as f.call(o, '!')

‘this’ keyword is set to object o. You get the idea. The only difference you should pay attention to is that the second parameter supplied to f.apply() is an array.

Comments on this entry are closed.

Previous post:

Next post: