473,503 Members | 2,066 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

'this' going out of scope

Hi everybody,

in the small snippet of code below, you can see two identical
debugMsg(this.myname) statements, one correctly returns "manu"
but the other returns "undefined". This is due to 'this' getting out
of scope. Is there a way I can retain the 'this' object inside the
function() block? So that I can affect the object calling this method
from there? Any workarounds instead?

Here's the code:

----------------------------------------------
function AreasManager()
{
this.myname = "manu";
}

AreasManager.prototype.addAreasFromXmlFile = function(xmlFile_)
{
debugMsg(this.myname);
var request = GXmlHttp.create();
request.open("GET", xmlFile_, true);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
var xmlContent = request.responseXML;
debugMsg(this.myname);
}
}
request.send(null);
}
----------------------------------------------

Thanks for your help.

Manu

Oct 22 '06 #1
6 1632
Emanuele D'Arrigo wrote:
Hi everybody,

in the small snippet of code below, you can see two identical
debugMsg(this.myname) statements, one correctly returns "manu"
but the other returns "undefined". This is due to 'this' getting out
of scope. Is there a way I can retain the 'this' object inside the
function() block? So that I can affect the object calling this method
from there? Any workarounds instead?
The value of the this keyword is determined entirely by how you call a
function, not by how you declare it. Try this post:

<URL:
http://groups.google.com.au/group/co...78eba47a1a7dc9
>
Or search for the recent thread with subject:

Assigning methods to objects, and assigning onreadystatechange to an
XMLHttpRequest -- an inconsistency?
>
Here's the code:

----------------------------------------------
function AreasManager()
{
this.myname = "manu";
}

AreasManager.prototype.addAreasFromXmlFile = function(xmlFile_)
{
debugMsg(this.myname);
The this value here refers to an instance of an AreasManager object
*provided* it is called as a method of an AreasManager object.

var request = GXmlHttp.create();
request.open("GET", xmlFile_, true);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
var xmlContent = request.responseXML;
debugMsg(this.myname);
It a common assumption that in the above case, the this value of the
anonymous function refers to the request object, but as the song says,
"it ain't necessarily so". The link above gives the reason why.
--
Rob

Oct 22 '06 #2
Rob, thanks for your help.

This closure thing is giving me an headache. I've gone through quite
a few posts and webpages on the matter and I feel fairly confused now.
I understand why it doesn't work, but I still can't quite understand
how
to make it work or how to change my approach to work around it.

I.e, now I tried this:

function AreasManager()
{
this.myname = "manu";
}

AreasManager.prototype.addAreasFromXmlFile = function(xmlFile_)
{
debugMsg(this.myname + "1");

var request = GXmlHttp.create();
request.open("GET", xmlFile_, true);

var self = this;
var req = request;
function handler()
{
debugMsg(self.myname + "2");
if (req.readyState == 4)
{
debugMsg(self.myname + "3");
}
}

request.onreadystatechange = handler();
request.send(null);
}

The first two debugMsg() statements work fine and will print out
the expected manu1 and manu2. But the flow never gets to
the third debugMsg() statement, because it's now the req object
to be out of scope. Why is it?

Shouldn't var req = request; act as var self = this; ??

What am I missing?

Thanks again for your help.

Manu

Oct 22 '06 #3
Emanuele D'Arrigo wrote:
This closure thing is giving me an headache. I've gone through quite
a few posts and webpages on the matter and I feel fairly confused now.
I understand why it doesn't work, but I still can't quite understand
how to make it work or how to change my approach to work around it.
You're alterations are almost correct, but you introduced a new error
not present in your original post.
AreasManager.prototype.addAreasFromXmlFile = function(xmlFile_)
[snip]
var req = request;
This is unnecessary, by the way. Simply use request - both are local
variables, and both will be available within the scope chain of the
function that follows. All this does is add a second reference.
function handler()
There's no need for this to be included as a function declaration. A
function expression, as in the original, will do.

[snip]
request.onreadystatechange = handler();
Your problem is here. Instead of assigning a reference to the function
to the property, you call the function and assign the return value.

[snip]
The first two debugMsg() statements work fine and will print out
the expected manu1 and manu2. But the flow never gets to
the third debugMsg() statement, because it's now the req object
to be out of scope. Why is it?
Because when the function is called, the readyState property isn't 4.
You should have checked that. :-)

[snip]

Mike
Oct 22 '06 #4
Aaaah!!! Thank you Michael!
At last I managed to come up with a working method:

AreasManager.prototype.addAreasFromXmlFile = function(xmlFile_)
{
var self = this;

var request = GXmlHttp.create();
request.open("GET", xmlFile_, true);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
var xmlContent = request.responseXML;
self.addAreasFromXmlElement(xmlContent);
}
}

request.send(null);
}

Thank you very much, this seems to work exactly as
I intended! In fact it's extremely similar to what I had
in the first place, except for the use of 'self'. Thank you
again.

Manu

Oct 22 '06 #5
Hi,

Emanuele D'Arrigo wrote:
Aaaah!!! Thank you Michael!
At last I managed to come up with a working method:

AreasManager.prototype.addAreasFromXmlFile = function(xmlFile_)
{
var self = this;

var request = GXmlHttp.create();
request.open("GET", xmlFile_, true);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
var xmlContent = request.responseXML;
self.addAreasFromXmlElement(xmlContent);
}
}

request.send(null);
}

Thank you very much, this seems to work exactly as
I intended! In fact it's extremely similar to what I had
in the first place, except for the use of 'self'. Thank you
again.

Manu
I would recommend using against "self", because in web-browser based
JavaScript, "self" means the same as "window", it's a predefined name.
It's hidden by the local "var" declaration, but it will confuse your
audience.
http://developer.mozilla.org/en/docs/DOM:window.self

Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Oct 22 '06 #6

Laurent Bugnion wrote:
I would recommend using against "self", because in web-browser based
JavaScript, "self" means the same as "window", it's a predefined name.
I was wondering why my editor did highlight it... thanks Laurent, will
do.

Manu

Oct 22 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
2155
by: Ali | last post by:
I have the following web page with a script in it. <html> <head> <title>Make Your Own Objects test</title> <script>
8
3358
by: TTroy | last post by:
I have a few questions about "scope" and "visibility," which seem like two different things. To me "visibility" of the name of a function or object is the actual code that can use it in an...
2
1761
by: Adam Clauss | last post by:
Basically, my question is in terms of performance and the garbage collector - Is there any difference between a) letting a variable simply go out of scope b) explicity setting it to null once I am...
29
1777
by: tmp123 | last post by:
I hope any of my post helps someone, specially to people who is learning C. Thanks to people who has teach me things I didn't know before. And to all... all... and all others, too much posts...
7
2206
by: relient | last post by:
Question: Why can't you access a private inherited field from a base class in a derived class? I have a *theory* of how this works, of which, I'm not completely sure of but makes logical sense to...
9
4011
by: Phrogz | last post by:
I'm trying to write an 'each' function for a JavaScript array that behaves like Ruby's Array#each. (It doesn't matter if you know Ruby to help with this question.) My problem is the scope of...
31
8435
by: Anamika | last post by:
Hello friends.... can anyone tell me what will happen when we do..."delete this"...
1
1104
by: sasha | last post by:
class Base{ public: std::ostream& operator<<( std::ostream& os, const string &str ) { return print(os); } void print(std:ostream& os){ os<<"Base\n";} };
112
5348
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions...
0
7205
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7287
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7348
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7467
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
4685
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1519
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
397
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.