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

I am a little confused as to what happens 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 bound, the handleWelcome context did not have access to the instance fields of my Javascript myproject.MyClass (understandable). Following the information here , I now have a class instance context. All is well and good.

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

I apologize for any non-Javascript idioms that I use - I am much more familiar with Java and probably use hodgepedia terms.

EDIT

At first, I had some questions about which argument was passed to the callback (in this case, an event with an object like goog.net.Xhrio), but the main question was bind, so I deleted the tangential q.

+6
source share
3 answers

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

JavaScript has first-class functions, but they are not inherited using the "this" value, so if you don't bind it, the value depends on how it is called:

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

Traditionally, if the value of "this" is not specified, undefined or null, then it is forcibly applied to the global one, this "window" is usually. However, if you are in strict EcmaScript 5 mode, the value remains unchanged (unspecified "undefined").

+9
source

It depends on what the Google code is doing, as it can reliably associate this with something when it calls your callback, but it was probably undefined.

That is, inside the google library there is an event handler that does something like:

  goog.whatever.randomHandler = function( foo ) { // ... if (config.benFlynnHandler) { config.benFlynnHandler.call( something_mysterious, someArgument ); } // ... 

Well, something_mysterious can be null , it can be some kind of semi-popular object, or who knows.

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

first this in this.handleWelcome is a reference to the parent class (function). the second is a link to the current function;

This is the most vague way I can explain this and maybe not 100% technically correct, but it should be close. They can hold anything or nothing.

The easiest way to see what is happening is to pass in both the console and see what to contain, possibly using firebug.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/903877/


All Articles