JavaScript call and apply quick reference

From Trephine

Jump to: navigation, search
« JavaScript scope piercing JavaScript classes »

[subscribe] Recent blog entries

Live Demos

JavaScript call and apply quick reference

My previous explanation of the JavaScript call and apply functions is probably too verbose for a casual reading. This quick reference gets to the point right away, and assumes you already understand JavaScript's treatment of objects and functions. If this seems unfamiliar to you, I urge you to read the original article instead.

The synopses of call and apply are as follows:

someFunction.call( thisObject, arg1, arg2, ... );
someFunction.apply( thisObject, arrayOfArguments );

Where:

  • someFunction is the function to execute, and
  • thisObject is the Object to treat as this

Note that whereas call() expects to be passed the this object followed by each argument, apply() expects a this object followed by an array of arguments to pass in. In both cases the extra arguments are optional.

To demonstrate, consider a simple function:

function greet( person ) {
  alert( "Hello " + person.name + ", I'm " + this.name );
};

The idea is that the greet() function is intended to be called by an object with a name property and passed a similar object as its person argument. Remember that in JavaScript, the this keyword is resolved when a function is executed, not when it's defined.

The following is a simple example of how to execute the greet function using call():

var alice = { name: "Alice" };
var bob = { name: "Bob" };
 
greet.call( bob, alice ); // alerts "Hello Alice, I'm Bob"
greet.call( alice, bob ); // alerts "Hello Bob, I'm Alice"

By contrast, here's a similar example using apply().

greet.apply( bob, [ alice ] ); // alerts "Hello Alice, I'm Bob"
greet.apply( alice, [ bob ] ); // alerts "Hello Bob, I'm Alice"

That's all there is to it. For a broader discussion of these useful functions in the context of more detailed scenarios, I encourage you to check out the original JavaScript call and apply article. Enjoy!

--Jim R. Wilson (jimbojw) 11:26, 6 April 2009 (UTC)
Personal tools