PDA

View Full Version : Objects: Passing via reference


w0lf42
05-24-2004, 06:43 PM
I am messing around with passing values to a function via reference and I am under the impression that if I pass an object such as an STRING object or ARRAY object, the function has direct access to the orginal object, which means I can change the values of the values in the object.

The sample code below confuses me. If you run it, you will notice that the ARRAY object will change the value from "November" to "December", but the STRING object does not.

In the head:
<script type="text/javascript">
<!--
function changeString(obj) {
obj = "December";
} // end function
function changeArray(obj) {
obj[0] = "December";
} // end function
// -->
</script>


In the body:
<script type="text/javascript">
<!--
var foo = new String("November");
var bar = new Array("November");
document.writeln(foo + " " + bar[0] + "<br \>");
changeString(foo);
changeArray(bar);
document.writeln(foo + " " + bar[0] + "<br \>");
// -->
</script>


Any suggestions as to why?

Thanks

n8thegreat
05-24-2004, 07:08 PM
In JavaScript all functions are called by value with one exception. If you pass an object or an array to a function and the called function modifies attributes or properites of the object/array, the callee of the function will then get the changes to the object/array.

i guess a String object isnt considered on Object object. Like i could define a string by just doing bob = "SDssd". it would be the same as doing bob = new String("SDssd"). its the same way with numbers and the Number() object. it will, however, pass by reference an html element object, and custom objects.