10

this.callThisFunction = this.callThisFunction.bind(this);

👆 is the stupidest thing I have ever seen.

Comments
  • 0
    Why?
  • 1
    The syntax basically says: "I am 'this'. I have a function. But still I have to call another function on said function to bind it to myself, because apparently it is not really mine. And then I assign the bound function to where the unbound function was."

    Which is basically the same as writing:

    this.property = this.property.prettyPrettyPleaseAssignTo(this);

    If it wasn't assigned before, how come I have to refer to the function using "this.function"? If it's not bound already, where does it live? Is it flying around somewhere?

    Even if we let go of the fact that the assignment part of the equation should already by the binding operation, the binding mechanism should be a method of 'this', not of the function. Calling 'bind' on the function means the function itself has a reference to 'this', not the other way around.
  • 1
    @BellAppLab this is very useful when dealing with JS event listeners because the function you pass as your callback often has its 'this' changed to something else (like 'window') against your will, so you can do this to guard against implementation-specific context changes and ensure that your callbacks always have the expected 'this' when you refer to them.

    In React in particular, this saves you from having to create a new bound function every time you register an event handler in an ES6 Class Component's render method, you can point straight to your instance's (pre-bound) method.
  • 0
    @bhan I understand the importance of the thing. But that's precisely why it is a shameless workaround, worthy of devRant's wk19.
  • 1
    u wrong as hell bruh
  • 0
Add Comment