[RESOLVED] Use parameter of function as return?
How would I do something like this:
Code:
var theVariable = "";
var wasSuccess = false;
function doSomething(theParameter)
{
theParameter = "I'm the parameter!";
return true;
}
wasSuccess = doSomething(theVariable);
alert(theVariable);
And it will alert "I'm the parameter!".
Basically I need to change the variable's value that's specified as a parameter. Not sure if it's possible to do with JavaScript, but I'm sure I've seen it done before.
Re: Use parameter of function as return?
You'll want to pass the parameter by reference.
http://php.net/manual/en/language.references.pass.php
*edit* Whoops... Thought I was in the PHP section. Take a look at this instead: http://snook.ca/archives/javascript/javascript_pass/
Re: Use parameter of function as return?
well, if it's displaying "I'm the parameter" in the alert box.... doesn't that answer your question?
Or are you asking if that will work? If that's the case, then it should have taken you all of 5 minutes to test that out. create an HTML file, add the script, open it and see what happens.
-tg
Re: Use parameter of function as return?
Call-time pass-by-reference is a headache. JavaScript doesn't support it. Instead, you could pass an object containing a property, and modify the value of that property.
But your example doesn't make a lot of sense, because the new value is known before the function call, and so the function call is redundant. Show us what you really need to do and we'll come up with a way to do it.
Re: Use parameter of function as return?
kfcSmitty got it spot on! That's exactly what I was trying to achieve.
Basically the reason I'm doing this is I've got a JS function that I use for AJAX. It's all fine when I'm updating the webpage, but when I want to update a JS variable, it's a different story.
Here's what I mean:
PHP Code:
var httpReqs = new Array;
function getFromServer(queryAndURL, idToUpdate)
{
var newUpper = 0;
httpReqs[httpReqs.length+1]=false;
newUpper=httpReqs.length;
if(navigator.appName == "Microsoft Internet Explorer")
{
httpReqs[newUpper] = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
httpReqs[newUpper] = new XMLHttpRequest();
}
httpReqs[newUpper].open("GET", queryAndURL, true);
httpReqs[newUpper].onreadystatechange=function()
{
if(httpReqs[newUpper].readyState == 4)
{
document.getElementById(idToUpdate).innerHTML = httpReqs[newUpper].responseText;
}
}
httpReqs[newUpper].send(null);
return 0;
}
I will be modifying this function so that when called, it updates what ever variable that's passed as a parameter.
Re: [RESOLVED] Use parameter of function as return?
Why don't you just pass the event handler in?
Code:
function getFromServer(queryAndURL, callback)
{
// ...
httpReqs[newUpper].onreadystatechange = callback;
// ...
}