Closure or Bind

2019-09-09 08:43发布

问题:

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?