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:
- As posted in comments below, CMS made mention of a great article.
- It should be mentioned that there is no true way to pass anything by reference in JavaScript. The first line has been changed from "by reference" to "as reference". This workaround is merely as close as you're going to get (even globals act funny sometimes).
- As CMS, HoLyVieR, and Matthew point out, the distinction should be made that
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!