0

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?

Robert Harvey
201k55 gold badges470 silver badges682 bronze badges
asked May 14, 2020 at 15:53
3
  • A code smell implies that there is a better way to perform the same action. Is there a better way to perform the same action? Commented May 19, 2020 at 8:41
  • @Kain0_0 I don't know whether there is. I lack the know-how. Like I said, this is my first real hands-on exposure to Javascript (aside from just tinkering over the years). Commented May 19, 2020 at 10:18
  • 1
    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 Commented May 19, 2020 at 13:16

1 Answer 1

2

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.

answered May 19, 2020 at 13:18
2
  • 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(?) Commented 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) Commented May 20, 2020 at 15:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.