AS3 httpservice - pass arguments to event handlers by reference
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 a way to do it by reference without searching through my array of search objects for the value returned in the result?
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.
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.
精彩评论