Is there an equivalent in JavaScript for PHP\'s reference passing of variables?
[PHP]:
function addToEnd(&$theRefVar,$str) { $theRefVar.=$str; } $myVar=\"H
Objects are passed as references.
function addToEnd(obj,$str)
{
obj.setting += $str;
}
var foo = {setting:"Hello"};
addToEnd(foo , " World!");
console.log(foo.setting); // Outputs: Hello World!
Edit:
foo
is a reference to an object and that reference is passed by value to the function.The following is included as another way to work on the object's property, to make your function definition more robust.
function addToEnd(obj,prop,$str)
{
obj[prop] += $str;
}
var foo = {setting:"Hello"};
addToEnd(foo , 'setting' , " World!");
console.log(foo.setting); // Outputs: Hello World!