rand0m86
rand0m86

Reputation: 3322

JavaScript call() function

I've started learning pure JS by John Resig's book and found quite unclear example with call() function:

function forEach (list, callback) {
    for (var i = 0; i < list.length; i++) {
        callback.call(list[i],i)
    };
}

var strings = [ 'hello', 'world', '!'];

forEach(strings, function(index){
    console.log(strings[index]);
});

How it works? Can anybody explain?

Upvotes: 2

Views: 116

Answers (1)

James Allardice
James Allardice

Reputation: 165971

The call method is used to invoke a function in a particular context (in other words, with a specific value for this). That example invokes the callback function in the context of the current list item, and passes in the value of i:

forEach(strings, function(index){
    console.log(this); // "String ['hello']" etc...
    console.log(index); // "0" etc...
});

If the callback function was invoked normally (without the call method) then the context would be either the global object or undefined (if the code is running in strict mode).

Upvotes: 3

Related Questions