Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct Javascript bind syntax?

I have found two ways of using Javascript's native bind as I migrate away from jQuery.proxy():

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

and

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 on() (or any function in its place). The former syntax is what I'm used to from $.proxy(), 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?

like image 866
D G Avatar asked Apr 19 '16 13:04

D G


People also ask

What is a bind in JavaScript?

bind is a method on the prototype of all functions in JavaScript. It allows you to create a new function from an existing function, change the new function's this context, and provide any arguments you want the new function to be called with.

Should you use BIND in JavaScript?

. bind() is used when you need to pass a callback (e.g. some sort of function reference), but you want the caller to call your function with a specific this value.

What is new binding in JavaScript?

Rule #3: The JavaScript new BindingA new keyword is used to create an object from the constructor function. let Cartoon = function(name, character) { this.name = name; this. character = character; this. log = function() { console.

What is default binding in JavaScript?

Default binding refers to how this is the global context whenever a function is invoked without any of these other rules. If we aren't using a dot and we aren't using call(), apply(), or bind(), our this will be our global object. Your global context depends on where you're working.


1 Answers

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't do what native bind does.

like image 96
T J Avatar answered Oct 11 '22 12:10

T J