Reputation: 1201
I'm reading someone's code and I see the following:
this.device_name.changes().onValue(this.changeName.bind(this))
From what I understand, onValue
takes a callback function, and that function is this.changeName.bind(this))
. Correct me if I'm wrong:
this
in a function call refers the object with which the function was called upon..bind(someObject)
method causes the function's this
to refer to someObject
instead, when the function gets executed.Knowing this (heh), this.changeName.bind(this)
seems redundant: the default value for this
when calling this.changeName
will be the same this
that is passed in the bind
parameter.
So! Can the function be safely refactored to simply this.changeName
with no differences in behavior?
Upvotes: 1
Views: 93
Reputation: 30401
No, the bind is very important here.
A function's this
pointer is set at the time the function is called. The call, in this case, is down inside whatever object is invoking the callback. Many objects just call with a this pointer either as null or (in the case of DOM objects) pointing to the DOM object itself.
Using the bind function this way returns a new function that hard-wired the this
reference to the value passed to bind. If you take out the bind, it'll completely hose up the this
pointer. It will DEFINITELY change the behavior.
Upvotes: 2