Pergunta

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?

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
scroll top