Click to See Complete Forum and Search --> : call by reference in JavaScript


jasongr
09-27-2004, 05:36 AM
Hello

I was wondering if it is possible to pass a variable by reference in JavaScript.
I was looking for it in my book, but couldn't find it.

Here is what I am trying to do:

var param = 'Success';
test(param);
function test(param) {
param = 'Success';

if (condition1) {
param = 'Failure';
return;
}

// return some value
}

alert(param);

I would param to change to 'Failure' if the condition is true.
I cannot use the return value, because it is used to return a valid value from the function.
I don't want to use global variables

thanks

Willy Duitt
09-27-2004, 06:21 AM
You could try looking here (http://www.sitepoint.com/forums/showthread.php?t=198366)....

.....Willy

baconbutty
09-27-2004, 06:24 AM
Sorry Javascript does not support passing by reference for simple types such as String, Number, or Boolean.

However, it does automatically pass by reference Objects, Functions, Arrays, HTMLElements and other complex objects.

Thus to solve your problem:-


var myObject=new Object();
myObject.myParameter="Success";
fTest(myObject); // Alters "Changed";


function fTest(anObject)
{
anObject.myParameter="Changed";
window.alert(anObject.myParameter);
}

Warren86
09-27-2004, 08:09 AM
Jason:
Is this what you would like to do?

<HTML>
<Head>
<Script Language=JavaScript>

var param = "Failure";

function testIt(isVar){

if (isVar == "Success"){return true}
if (isVar == "Failure"){return false}
}

function isResult(isVar){

tmp = testIt(isVar);
alert(tmp);
}

</Script>
</Head>
<Body>
<input type=button value="Test" onClick="isResult(param)">
</Body>
</HTML>

------- Or :
<HTML>
<Head>
<Script Language=JavaScript>

var param = "Failure";

function testIt(isVar){

if (isVar == "Success"){return true}
if (isVar != "Success"){return false}
}

function isResult(isVar){

tmp = testIt(isVar);
alert(tmp);
}

</Script>
</Head>
<Body>
<input type=button value="Test" onClick="isResult(param)">
</Body>
</HTML>