heartyporridge
heartyporridge

Reputation: 1201

Is this.someFunction.bind(this) redundant?

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:

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

Answers (1)

Chris Tavares
Chris Tavares

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

Related Questions