IIFE vs bind() for event/callback function
Asked Answered
H

1

3

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?

Hickson answered 20/4, 2016 at 14:36 Comment(2)
You're not passing the event parameter on to sayHello, and it's considerably longer.Snipe
You can post as an answer, @Bergi, and I'll mark as the accepted answer.Hickson
S
4

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.

Snipe answered 10/5, 2016 at 17:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.