Skip to content Skip to sidebar Skip to footer

Is It Right To Avoid Closures Using Bind In Javascript?

Are closures too bad for browser's memory? Is avoiding closures using bind in JavaScript a good way? Existing code: var oControl = new Control({ var self = this; click: f

Solution 1:

I would suggest this:

var oControl = new Control({
    click: this.performAction.bind(this)
});

There appears to be no reason in your code for the self variable at all and if the click handler is just going to call your other method, then you may as well use the .bind() without the wrapper function.

FYI, .bind() creates a closure itself so don't be thinking that using .bind() is eliminating a closure. It is eliminating you having to hand-code a closure variable which is what makes it handy to use and makes your code look cleaner.

As for your other questions:

  1. Are closures too bad for browser's memory?

Closures do use some additional memory. Unless you have a zillion of them, that extra memory is not likely material. And, .bind() likely also uses a closure in its implementation (the this pointer has to be stored somewhere).

  1. Is avoiding closures using bind in JavaScript a good way?

.bind() is very useful and you should feel free to use it when it serves your purpose. Whether to use your first block of code with your own closure variable, your second block of code with a wrapper function using .bind() or my suggestion is largely a matter of opinion on coding style and opinion on cleanliness of implementation. All can work fine and there is unlikely to be a meaningful difference in performance or memory usage.

Post a Comment for "Is It Right To Avoid Closures Using Bind In Javascript?"