2

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?

1
  • 2
    How much do you know about call? i.e. what's your starting point? Have you read the documentation, e.g. on MDN? The first argument to call is the this pointer for your method and the second (and subsequent) are the ones that gets passed to your function as arguments. Commented Oct 18, 2013 at 10:40

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.