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?
function currying via the
bind()
method
It's partial application actually.
Are there any disadvantages to swapping out the IIFE for
bind
?
The difference between your approaches is that bind
passes through further parameters instead of only calling sayHello
with name
. In this case, the event argument will be passed to the handler instead of being ignored. Of course this can be fixed (using the arguments
object or ES6 rest+spread), but it only makes it more complicated and errorprone.
And that's the major disadvantage imo: It's considerably but unnecessarily longer. I prefer conciseness.