Aman K
Aman K

Reputation: 65

Is it right to avoid closures using bind in JavaScript?

  1. Are closures too bad for browser's memory?
  2. Is avoiding closures using bind in JavaScript a good way?

Existing code:

var oControl = new Control({
    var self = this;
    click: function(e){ //closure that's accessing self var
        self.performAction();
    }
});

I have been told to avoid writing code as shown above. Reason given - a closure is created in the above code. I have been suggested using bind to overcome the above problem.

Modified code:

var oControl = new Control({
    var self = this;
    click: function(e){ //Not a closure  
        this.performAction(); //Is this more readable?
    }.bind(self)
});

I am not too sure if the modified code is more readable. Somehow, I feel that this is in a way polluted. Probably, there are better ways to avoid closures? But, is there a real need to avoid them in the first place?

Upvotes: 3

Views: 783

Answers (1)

jfriend00
jfriend00

Reputation: 707326

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.

Upvotes: 4

Related Questions