473,320 Members | 1,993 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Should an object declared in a function persist after function exits?

Hello,

I assigned a new object to a local variable ("req") in a function (see
below). The local variable "req" is obviously destroyed when the
function exits, but should the object referenced by the variable live
on?

It seems that it does (and I want it to), but is this correct? I
thought that local variables (and objects) are destroyed when the
function exits? I declared a callback function--function () {
processReqChange (req); };--with the variable that is called later and
it all seems to work okay.

Thank you!

function SendRequest(site,size,position,id) {

var msg="targetsite=" + encodeURI(site)+ "&id=" + encodeURI (id)+
"&targetsize=" + encodeURI (size)+"&position=" + encodeURI(position);

// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) { // Safari, Mozilla
var req = new XMLHttpRequest(); //create new local object
if (req.overrideMimeType) {
//set type accordingly to anticipated content type
//req.overrideMimeType('text/xml');
req.overrideMimeType('text/html');
}
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
var req = new ActiveXObject("Microsoft.XMLHTTP"); //create new
local object
}
else {
alert("Your browser does not support XMLHTTP")
}
if (req) {
var url_to_use=url+'?unique='+ new Date().getTime ();
req.open('POST', url_to_use, true); //Open before assign callback to
ensure IE ability to repeat process
req.onreadystatechange = function () { processReqChange (req); };
//Make a new function that calls processReqChange with this object
req.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", msg.length);
req.setRequestHeader("Connection", "close");
req.send(msg);
}
}

Oct 18 '06 #1
2 2175
Jeff wrote:
I assigned a new object to a local variable ("req") in a function (see
below). The local variable "req" is obviously destroyed when the
function exits, but should the object referenced by the variable live
on?
It can.

What you're describing is called a closure. Read this:
http://www.jibbering.com/faq/faq_notes/closures.html

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 18 '06 #2
Jeff wrote:
Hello,

I assigned a new object to a local variable ("req") in a function (see
below). The local variable "req" is obviously destroyed when the
function exits,
It isn't destroyed when the function exits.

SendRequest is declared in the global scope, and is therefore
instantiated when the code is first loaded into a browser (or other
host environment). At that point, req is created since it's declared
with the var keyword inside SendRequest.

Later, when SendRequest is called, an XMLHttpRequest object is created
and a reference to it assigned to req, so it now has a value.

Still later, inside SendRequest, you execute a function statement that
assigns an anonymous function to the onreadystatechange handler of the
XMLHttpRequest object referenced by req. When you do that, the
activation object of SendRequest is added to the anonymous function's
scope chain, thereby keeping req in scope for the anonymous function
and preventing the object it references from being garbage collected
(and create a closure).

At some later time, the onreadystatechange hanlder calls the anonymous
function, which calls processReqChange(req), using req to pass a
reference to the XMLHttpRequest object created when SendRequest was
called.

Even if you hadn't done the above, req doesn't get "destroyed" when the
function ends, it just goes out of scope. In that case, the object
referenced by req may be destroyed at some later time according to the
rules for garbage collection.
but should the object referenced by the variable live on?
As long as something in scope has a reference to it, it will not be
garbage collected. This may help:

<URL: http://www.jibbering.com/faq/faq_not....html#clIRExSc >
It seems that it does (and I want it to), but is this correct? I
thought that local variables (and objects) are destroyed when the
function exits?
Local variables exist as long as the objects they belong to exist.

[...]
function SendRequest(site,size,position,id) {

var msg="targetsite=" + encodeURI(site)+ "&id=" + encodeURI (id)+
"&targetsize=" + encodeURI (size)+"&position=" + encodeURI(position);

// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) { // Safari, Mozilla
var req = new XMLHttpRequest(); //create new local object
[...]
req.onreadystatechange = function () { processReqChange (req); };
When the above statement is evaluated, the right hand side creates an
anonymous function that has SendRequest's activation object (and hence
req) on its scope chain. When the onreadystatechange handler calls the
anonymous function, it uses req to pass a reference to the object to
processReqChange.

Without testing, it seems reasonable that you could use:

req.onreadystatechange = function () { processReqChange (this); };

on the basis that the anonymous function is assigned as a method of the
XMLHttpRequest object, and therefore when it's called by the
onreadystatechange event, its this value will be that object.

[...]

--
Rob

Oct 18 '06 #3

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

Similar topics

1
by: Randy Jackson | last post by:
I'm attempting to debug some code that uses the System function. When the function is called, it returns Error 1. Does anyone know what that error might be, or where I can find a list of error...
4
by: Christian Seberino | last post by:
I wrote some C functions and successfully imported them into Python. All is apparently well but there is one question about the object returned by the C function that is bugging me... Take for...
2
by: Jakob Bengtsson | last post by:
Hi, I have a form (which cannot be serialized). In the form's code I declare an object like this (never mind the object nor class name, it's for illustration only): Private WithEvents...
22
by: Dr Duck | last post by:
GDay all, Something seems odd to me.... I wrote a simple C# function public void bind(ref object a, ref object b, bool atob) { if(atob) b = a; else
30
by: Javaman59 | last post by:
I come from a background of Ada and C++ programming, where it was considered good practice to explicitly initialize every variable. Now that I'm programming in C# I think that it would be best...
2
by: Nathan Sokalski | last post by:
I would like to access variables and functions that I declare in the Global.asax.vb file. However, I am having trouble doing that. What does the declaration have to look like in the Global.asax.vb...
3
by: Adriano | last post by:
Hello, when I try to print something, either DataGrid or from Crystal Report viever the folowing error message appears and cancels printing: Object reference not set to an instance of an...
5
by: rishi.shah | last post by:
I wanted to know how the compiler creates and allocates memory for an object in C++. When I say Foo obj where Foo is a class does the memory for the attributes of class Foo get allocated on the...
3
by: George2 | last post by:
Hello everyone, 1. Returning non-const reference to function local object is not correct. But is it correct to return const reference to function local object? 2. If in (1), it is correct...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.