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.
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").
It depends on what the google code does, since it could concievably bind this
to something when it invokes your callback, but it was probably undefined.
That is, inside the google library somewhere, it's got an event handler that does something like:
goog.whatever.randomHandler = function( foo ) {
// ...
if (config.benFlynnHandler) {
config.benFlynnHandler.call( something_mysterious, someArgument );
}
// ...
well "something_mysterious" could be null
, it could be some semi-interesting object, or who knows.
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