Using Call And Apply Methods

Sorry, for the late post. Mint is about to launch v1.1 and much of the remaining work is user interaction. I have already worked 60 hours this week and it is only Saturday morning. Anyway, enough bitching…

Today, we are going to examine the native JavaScript Function methods: call and apply. Both methods are used to set the execution scope of the Function you are calling, but with "call" you pass in each parameter directly to the Function, whereas with "apply" you pass in an array whose members are applied to the Functions parameters.

Here is a simple example of each:

var Foo = function(arg1, arg2, arg3) {
	// do something
var arr = [a, b, c];, 1, 2, 3);
Foo.apply(window, arr);

In this example we are creating a Function "Foo" with parameters: arg1, arg2, and arg3; we also create an array with members: a, b, and c. Using the "call" method we set the execution scope of Foo to "window", then pass in each argument (arg1, arg2, arg3) explicitly. The "apply" method also sets the execution scope of Foo to "window", but instead passes in an array. The members of the array will be applied to Foo, where the array member at position n, will be applied to the nth parameter of Foo. With both methods if you pass in too few parameters, the remaining parameters will be set to "undefined"; and if you pass it too many, the extra parameters will be ignored.

This example was rather simple and since the execution scope of Foo was "window" already, we have not really accomplished much. So, lets create another Function "Bar" that leverages the native "prototype" Object:

var Bar = function(id) {
	this.node = document.getElementById(id);

Bar.prototype = {
	callFoo: function(arg1, arg2, arg3) {, arg1, arg2, arg3);
	applyFoo: function() {
		Foo.apply(this, arguments);

var barObj = new Bar(someElementId);
barObj.callFoo(1, 2, 3);
barObj.applyFoo(a, b, c);

In this example, when instantiated, Bar will have members "applyFoo" and "callFoo", and will contain a DOM reference "node". Now "callFoo" and "applyFoo" will execute Function Foo with the scope of the "barObj". Therefore, the code inside of Foo will have access to all member Functions and properties of "barObj", such as the "node", on Foos "this" Object. Many Frameworks use thse methods in conjunction with their Event and/or AJAX Handler Systems, so that you can specify the scope of the callback Function. In this case, we are not that sophisticated, "callFoo" executes Foo with up to three explicit arguments, and "applyFoo" will pass any number of supplied arguments directly into Foo. This means "applyFoo" acts like a proxy Function of Foo, only changing Foos execution scope.

Next week, I will be demonstrating how to create event handler Functions that maintains scope. Then you will see how to use "call" and "apply" in a working system.