r/coffeescript • u/xjohnseanx • Nov 14 '14
Passing functions as parameters
Hey I am working through http://eloquentjavascript.net/ and decided to use coffeescript. However, I am having some issues getting a few of the examples to work.
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
forEach(["Wampeter", "Foma", "Granfalloon"], console.log);
// → Wampeter
// → Foma
// → GranfalloonHow would you write something like this using coffeescript? I already tried http://js2coffee.org/ after not being able to come up with a solution myself
4
Upvotes
View all comments
Show parent comment
1
u/Corkscreewe Nov 14 '14
The Illegal invocation is because you are calling console.log with different 'this' inside. You can fix it:
or by using a slightly modified function:
For details, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call