473,624 Members | 2,685 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.m yname) 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.pr ototype.addArea sFromXmlFile = function(xmlFil e_)
{
debugMsg(this.m yname);
var request = GXmlHttp.create ();
request.open("G ET", xmlFile_, true);
request.onready statechange = function()
{
if (request.readyS tate == 4)
{
var xmlContent = request.respons eXML;
debugMsg(this.m yname);
}
}
request.send(nu ll);
}
----------------------------------------------

Thanks for your help.

Manu

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

in the small snippet of code below, you can see two identical
debugMsg(this.m yname) 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 onreadystatecha nge to an
XMLHttpRequest -- an inconsistency?
>
Here's the code:

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

AreasManager.pr ototype.addArea sFromXmlFile = function(xmlFil e_)
{
debugMsg(this.m yname);
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("G ET", xmlFile_, true);
request.onready statechange = function()
{
if (request.readyS tate == 4)
{
var xmlContent = request.respons eXML;
debugMsg(this.m yname);
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.pr ototype.addArea sFromXmlFile = function(xmlFil e_)
{
debugMsg(this.m yname + "1");

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

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

request.onready statechange = handler();
request.send(nu ll);
}

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.pr ototype.addArea sFromXmlFile = function(xmlFil e_)
[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.onready statechange = 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.pr ototype.addArea sFromXmlFile = function(xmlFil e_)
{
var self = this;

var request = GXmlHttp.create ();
request.open("G ET", xmlFile_, true);
request.onready statechange = function()
{
if (request.readyS tate == 4)
{
var xmlContent = request.respons eXML;
self.addAreasFr omXmlElement(xm lContent);
}
}

request.send(nu ll);
}

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.pr ototype.addArea sFromXmlFile = function(xmlFil e_)
{
var self = this;

var request = GXmlHttp.create ();
request.open("G ET", xmlFile_, true);
request.onready statechange = function()
{
if (request.readyS tate == 4)
{
var xmlContent = request.respons eXML;
self.addAreasFr omXmlElement(xm lContent);
}
}

request.send(nu ll);
}

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
2168
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
3367
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 actual program. To me "scope" of the name of a function or object are the general rules for the areas of a program that can through a declaration, have "visibility."
2
1770
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 done with it I have no particular reason to think that b) would gain me anything, but I thought maybe it would be a sure sign to the garbage collector that Yes, you can go ahead and remove the object. Thanks!
29
1799
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 about nothing, too much calls to "skin" and "group habits". Something not seen in other usenet groups. Too much for my taste. I must end posting on this group.
7
2227
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 me. So, I'm here for an answer (more of a confirmation), hopefully. First let me say that I know people keep saying; it doesn't work because the member "is a private". I believe there's more to it than just simply that... Theory: You inherit,...
9
4014
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 'this' inside the iterator callback. I would like it to be the same as the object that called the each() on the array. Right now I have to do that with a closure or an explicitly-passed 'this' scope. For example: function Person( inName, inCats ) {
31
8460
by: Anamika | last post by:
Hello friends.... can anyone tell me what will happen when we do..."delete this"...
1
1115
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
5417
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 that may print some messages. foo(...) { if (!silent)
0
8251
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8182
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8635
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8352
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8494
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7178
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6115
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
1496
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.