Frage

I am doing a project for a client where I am getting my first real heavy, hands-on exposure with Javascript.

Since I have learned about adding .bind(this to callback functions, I find I am doing it everywhere, and I wonder whether it is excessive and whether it's good practice, or whether I am structuring my code badly.

Is it normal to have .bind(this) on nearly every callback?

War es hilfreich?

Lösung

Nope, you pretty much need to do this. If you call the functions of an object from the prototype, the this won't be bound to the object you call it on.

By doing this.fooMethod = fooMethod.bind(this);, you're making the object have its own instance method store a bound version of fooMethod. Calling fooMethod on that object will now call the function from its instanve variable, not from its prototype, with this appropriately bound.

The only real alternative is to use arrow notation, instead:

this.fooMethod = () => fooMethod();

But it gets repeated ad nauseam, just the same.

Lizenziert unter: CC-BY-SA mit Zuschreibung
scroll top