Closure or Bind

穿精又带淫゛_ 提交于 2019-12-12 02:56:26

问题


Is there any difference between limiter 1 and limiter 2?

var limiter1 = function(limiter){
   return function(item){
      return item > limiter;
   };    
};
var limiter2 = function(limiter){
   return function(limiter,item){
      return item > limiter;
   }.bind(this,limiter);
};

回答1:


In most cases, they will function identically. However...

If you ever start to actually use the value of this, the function returned by limiter1 will be unbound (so a consumer could change the value with a call to Function.prototype.bind). In limiter2, it's locked down with the initial bind call.

Also, they use different levels of scope to get the limiter variable. Depending on the engine, you could have a (minute) difference in performance.




回答2:


The .bind algorithm is a lot more complicated than wrapping a function with another function. However, most of the time it does not matter. I think that using native .bind usually provides for more readable and maintainable code - which is a big plus.

You can see more about this Why is bind slower than a closure?



来源:https://stackoverflow.com/questions/34359738/closure-or-bind

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