Danger Genti Danger Genti - 10 months ago 17
Javascript Question

What is the correct Javascript bind syntax?

I have found two ways of using Javascript's native

as I migrate away from jQuery.proxy():

this.thing.on(event, someHandler.bind(this))


this.thing.on(event, someHandler).bind(this)

As far as I can tell, they both do the same thing, but I'm worried that the latter might cause issues in the
(or any function in its place). The former syntax is what I'm used to from
, and to me looks like it's explicitly binding to the handler, so I'm leaning towards using that syntax.

Are these two lines actually doing the same exact thing? And if not, which is the safer option?

UPDATE: Okay, I'm an idiot. I completely failed to realize that the latter was using jQuery's
and not the native. They do, however, do the same thing in my particular case.


In the first case:

this.thing.on(event, someHandler.bind(this))

The native bind is invoked, and it'll work as you expect.

In the second case,

this.thing.on(event, someHandler).bind(this)

The jQuery on() method will return a jQuery object to which the events where bound, and when you call bind() on a jQuery object, jquery bind() method is being invoked, and it doesn'tdo what native bind does.