Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do you return a parameter

Status
Not open for further replies.

xwb

Programmer
Joined
Jul 11, 2002
Messages
6,828
Location
GB
Have a look at the following
Code:
function struct () {
   this.value = 0;
}

// Direct parameter
function setdirect (xx) {
   xx += 10;
}

function setindirect (xx) {
   xx.value += 10;
}

var yy = new struct ();
WScript.echo (yy.value);
setdirect (yy.value);
WScript.echo (yy.value);
setindirect (yy);
WScript.echo (yy.value);
What I get is 0 0 10 i.e. setdirect doesn't work but setindirect does.

It looks like the only way I can modify a parameter in a function is to pass a structure to it. Is this assumption correct or is there a "correct" way of modifying a parameter? Is there a way of getting round the call-by-value mechanism?
 
You have to pass an object if you want to pass parameters by reference rather than by value... So something like:

Code:
var someFunc(xx) {
   xx.myval += 10;
};

var myobj = { myval: 10 };
alert(myobj.myval);
someFunc(myobj);
alert(myobj.myval);

Hope this helps,
Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
To: op
If you want (js) official statements, the general rules are these.
js-documentation said:
Numbers and Boolean values (true and false) are copied, passed, and compared by value.
Objects, arrays, and functions are copied, passed, and compared by reference.
ref
Substantially the same is given by D Flanagan "Javascript - The Definitive Guide" (4th ed.) section 11.2.
 
js-documentation said:
Last, strings are copied and passed by reference, but are compared by value.
Flanagan named it "immutable". ECMA spec also has special note on the special implementation of string for efficient manipulation.
 
From your answers, I guess there isn't if it is a number or boolean. Thanks for the confirmation.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top