IIFE vs bind() for event/callback function

懵懂的女人 提交于 2019-12-10 19:27:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/36747209/iife-vs-bind-for-event-callback-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!