0

I'm writing a function which will allow me to display the values of an array by passing another function as a value.

This code works just fine:

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}
forEach(["foo", "bar", "qux"], alert);

But it throws and error if I try to pass a function with a property:

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}
forEach(["foo", "bar", "qux"], console.log);

If I do this: action.log(array[i]); it works just fine, but that would only allow me to pass functions with a .log property. Is there any way I can write a function which allows me to pass another function and property as a value?

1

3 Answers 3

3

The problem isn't using a method of an object, it's a console.log specific problem. Bug report here. For console.log specifically, you can bind context to it, for example:

forEach(["foo", "bar", "qux"], console.log.bind(console));

Other methods will work fine, for example:

var x = {
    test: function(str){
        alert(str);
    }
}

forEach(["hello", "world"], x.test);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use something like

function forEach(array, action) {
for (var i = 0; i < array.length; i++)
  action(array[i]);
}
forEach(["foo", "bar", "qux"], function(x){ return console.log(x) });

Comments

0

In Chrome, it is expected because console.info expects its "this" reference to be console, not window. Otherwise, I found it working in Firefox 32 / IE.

https://code.google.com/p/chromium/issues/detail?id=48662

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.