Search code examples
javascriptscopethisgoogle-closure

Understanding "this" context with goog.bind and goog.net.Xhrio.send


I am a little bit confused as to what happen when I call the following code:

goog.net.XhrIo.send("/welcome", goog.bind(this.handleWelcome, this));

I have a function with this signature:

myproject.MyClass.prototype.handleWelcome = function(response)

Before I was binding, the context of handleWelcome did not have access to instance fields of my Javascript class myproject.MyClass (understandably). Following the information here, I now have the context of the class instance. All well and good.

What was the context of "this" before I made the change?

Please excuse any non-Javascript idioms I'm using -- I'm much more familiar with Java and am probably using a hodgepodge of terms.

EDIT

Initially I had some questions about what argument was being passed to the callback (in this case an event with a target of of type goog.net.Xhrio) but the main question is about about this and bind, so I removed the tangential q's.


Solution

  • goog.bind is equivalent to function.prototype.bind, but that the first parameter is the function to be bound to, the second the "this" value that should be bound and any remaining parameters are bound to the functions formal parameters.

    JavaScript has first class functions, but they aren't inheritly bound with a "this" value, so unless you bind it, the value depends on how it is called:

    var x = { f : handler };
    x.f(); // handler is called with "x" as the this value.
    handler(); // unspecified this
    

    Traditionally, if "this" value is unspecified, undefined, or null then it is coerced into the global this, "window" usually. However, if you are running in EcmaScript 5 strict mode, the value remains unchanged (unspecified is "undefined").