1

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:

  • The default value of this in a function call refers the object with which the function was called upon.
  • The .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?

heartyporridge
  • 1,011
  • 7
  • 24

1 Answers1

2

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.

Chris Tavares
  • 24,202
  • 3
  • 43
  • 62
  • Ah, I'm starting to understand now. Suppose `onValue` looks like `function (callback) { ... callback() }`. When `callback()` runs, what is it's default `this` value (the value without `bind`)? – heartyporridge Jul 24 '15 at 18:10
  • 1
    There's one [very useful question](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) (and an answer to it, of course). – raina77ow Jul 24 '15 at 18:11
  • 1
    Since the call is `callback()`, not `someObject.callback()`, the `this` would be null. Or maybe undefined, I'm not sure off the top of my head. But definitely not anything useful. – Chris Tavares Jul 24 '15 at 18:12