JavaScript Function Call() Operator

JavaScript has become one of my favorite languages. It is extremely flexible and powerful. It is not hard picking up the basics if you have programmed Java or C# before. But there are many features that are very hard to emulate or simply not possible in those languages. One example is the Function object’s call() operator. It allows execution of any function in the context of an object passed into the function, or, in other words, changing the this reference a function uses for the duration of the call.

Here is anĀ  example:

// declare a function using "this" reference
function add(){
    var sum = 0;
    for (var i in this){
        sum += this[i];
    }
    return sum;
}

// Results in a concatenated string
// of the objects in the global scope
// including its own definition
alert(add());

// Results in "10"
var array = [1,2,3,4];
alert(add.call(array));

// Also results in "10"
var obj = {"one" : 1, "two" : 2, "three" : 3, "four" : 4};
alert(add.call(obj));

A common usage for this feature is to mimick inheritance for JavaScript objects by allowing constructor chaining. An example is Yahoo!’s YUI JavaScript Framework. But you also can use it for callback functions or setTimeout functions that execute in a different scope (i.e. the this reference points to a different object) than your callback function needs.

Further reading about this feature can be found at Mozilla Developer Center.

Anke


JavaScript

Written by: |

Connect with us: