Skip to content Skip to sidebar Skip to footer

Closure Or Bind

Is there any difference between limiter 1 and limiter 2? var limiter1 = function(limiter){ return function(item){ return item > limiter; }; }; var limiter2 = fun

Solution 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.

Solution 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?

Post a Comment for "Closure Or Bind"