Say, for example, I need to register an onclick
event that calls another function sayHello()
to say hello, with its parameter as a variable available in the current scope.
I could use IIFE to inject the variable into the scope of the anonymous function as follows:
var currentName = "James";
something.onclick = (function(name) {
return function() {
sayHello(name);
};
})(currentName);
However, I could also use a version of function currying via the bind()
method as follows:
var currentName = "James";
something.onclick = sayHello.bind(null, currentName);
Despite the fact that using the IIFE approach would let you do more than just one function call in the anonymous method, are there any disadvantages to swapping it out for the currying approach?
sayHello
, and it's considerably longer. – Snipe