On Thu, 08 Jun 2006 10:41:38 +0200, Stefan Mueller wrote:
I'd like to write a function 'double_values' which doubles two values.
var value1 = 5;
var value2 = 20;
alert("1) Value 1: " + value1 + " / Value 2: " + value2);
double_values(value1, value2);
alert("4) Value 1: " + value1 + " / Value 2: " + value2);
...
//-------------------------------------------------------
function double_values(a, b) {
alert("2) A: " + a + " / B: " + b);
a = a * 2;
b = b * 2;
alert("3) A: " + a + " / B: " + b);
}
Output:
1) Value 1: 5 / Value 2: 20
2) A: 5 / B: 20
3) A: 10 / B: 40
4) Value 1: 5 / Value 2: 20
I'm wondering why the output 4) shows
4) Value 1: 5 / Value 2: 20
and not
4) Value 1: 10 / Value 2: 40
What do I have to do to return both values a & b to value1 & value2?
Stefan
The problem is that in javascript function parameters are passed by value,
so the variable inside the function is a copy of the original variable,
not the variable itself.
One way round this is to use an object, like this (not tested):
var obj={val1:5, val2:20};
alert("val1:"+val1+" val2:"+val2);
doubleValues(obj);
alert("val1:"+val1+" val2:"+val2);
function doubleValues(object) {
object.val1*=2;
object.val2*=2;
}
In this case, 'obj' and 'object' are both pointers to an object that is
created by the {val1:5,...} line, and kept in memory until all the
pointers to it have been reassigned.
Your example is like if you give someone (jim) a piece of paper with a
number on it, but when you give it to them they copy the number onto their
own piece of paper. Jim doing maths on his piece of paper won't change
what's on yours.
The object example is more like this:
- first you ring fred (the object) and give them two numbers.
- then you give jim (the function) a piece of paper with fred's phone
number on it (the pointer). He copies it down.
- then he rings fred, asks for the numbers, doubles them, and tells fred
the answer.
- when you ring fred again, you'll get the new numbers.
I hope this is helpful rather than patronising...