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?
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.
. 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With