What is happening is that the function setVariableValue()
receives only the value of the variables test
, test2
and test3
. Then within the function, its operation is executed successfully, but on top of variables that will cease to exist as soon as the function returns (will leave the scope).
Therefore, normally we call a function, already assigning the result to the variable itself:
test = setVariableValue(test, 20); // atribui o resultado a 'test'
In this case, your role should have a return
:
function setVariableValue(variable, value) {
// return necessário para que a função retorne algum valor!
return variable * value;
}
var test = 10;
test = setVariableValue(test, 20);
document.writeln(test); // Resultado: 200
A second way to solve - Use the variable itself within the function:
var test;
function setVariableValue(value) {
test = value;
}
setVariableValue(12);
document.writeln(test); // Resultado: 12
And a third way - Using objects:
function setVariableValue(variable, value) {
variable.value = value;
}
var test = [], test2 = [], test3 = [];
setVariableValue(test, 20);
setVariableValue(test2, "Ola");
setVariableValue(test3, 1000);
document.writeln(test.value);
document.writeln(test2.value);
document.writeln(test3.value);
As objects, what is passed to the function ends up being a reference, and when changing an attribute of this object, the change persists.