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?
1 Answer 1
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.
-
Thanks! That tells me all I need to know. I was worried that, because I find myself doing it so often, I must be doing something wrong. I have not come across this in other languages, but maybe it's because they don't rely on callbacks so much(?)mydoghasworms– mydoghasworms2020年05月20日 14:28:37 +00:00Commented May 20, 2020 at 14:28
-
2@mydoghasworms Nah, it's just because every other language (that I know of) has method references that are either unbound (and need to be bound to a target object, by some means), or bound (already have the target object set). JS is the only language I know of in which has unbound method references, for this
this
is implicitly set (almost always to the wrong thing)Alexander– Alexander2020年05月20日 15:02:50 +00:00Commented May 20, 2020 at 15:02
bind(this)
is a lanugage-smell, that's it's jank and broken and definitely not worthy of its nomination for "universally runnable language" lol