views:

372

answers:

2

I have this code:

var service:HTTPService = new HTTPService();
if (search.Location && search.Location.length > 0 && chkLocalSearch.selected) {
    service.url = 'http://ajax.googleapis.com/ajax/services/search/local';
    service.request.q = search.Keyword;
    service.request.near = search.Location;
} else
{
    service.url = 'http://ajax.googleapis.com/ajax/services/search/web';
    service.request.q = search.Keyword + " " + search.Location;
}
service.request.v = '1.0';
service.resultFormat = 'text';
service.addEventListener(ResultEvent.RESULT, onServerResponse);
service.send();

I want to pass the search object to the result method (onServerResponse) but if I do it in a closure it gets passed by value. Is there anyway to do it by reference without searching through my array of search objects for the value returned in the result? Sorry, this is simple but it's been a long day...

+1  A: 

I'm not quite sure what you want to do here.

Parameters are indeed passed by value. In the case of objects (and by object here I mean everything that has reference semantics, i.e. everything but Booleans, Number, ints, Strings, etc), a reference to them is passed by value, so in your function you have a reference to the original object, not a reference to a copy of the object.

So, if you want to dereference the object and change some value or call some method on it, you'll be ok. The only thing that wont work is changing the reference itself; i.e. you can't null it out or assign a new object to it:

function dereferenceParam(param:Object):void {
    param.someInt = 4;
    param.someMethod();
}

function reassignParam(param:Object):void {
    param = null;
    //  or
    param = new Object(); 
}

dereferenceParam() will work as most people expect, reassignParam won't.

Now, the only possible "problem" I think you could have as per your last paragraph would be that you want to remove or null out the search object from some array you have. I'm afraid in that case, the only way would be to loop through the array.

Juan Pablo Califano
i want to pass search to onServerResponse.
Shawn Simon
Yes, but I fail to see why using your closure approach won't work. I guess maybe you want to remove the search object from your array, in which case you need to access the array. Otherwise, the search param you'll get is a copy of a reference to the original object. As long as you use the reference, you'll get access to the original object. So, if you want to change a value of the search object or call some method on it, you should have no problems.
Juan Pablo Califano
no, i get a reference to a copy of the object, not a copy of the reference.
Shawn Simon
A: 

How are you determining that you have received a copy of the object?

To my knowledge, (non-intrinsic) objects are almost never copied by value. The only exception are dispatched Event objects, but that is explicitly documented.

Richard Szalay