I was trying to work with objects as function arguments (pass as reference rather than value) and noticed something that to me seems odd, and I'd like to know why this is working this way.
Okay, let's say I have two JavaScript programs called onload, with one minor change between the versions...
The first program's modifying function assigns the argument as such:
data.fruit = "Mango";
//This program *will* update the data.fruit in the scope of main() with "Mango".
function modify(data) {
data.fruit = "Mango";
alert(data.fruit+"\nmodify();");
}
function main(){
var data= {"fruit":"Apple"};
modify(data);
alert(data.fruit+"\nmain();");
}
main();
The second program's modifying function re-assigns the value of the argument object as such:
data = {"fruit" : "Mango"};
//This program *ignores* updating the object in the scope of main.
function modify(data) {
data = {"fruit" : "Mango"};
alert(data.fruit+"\nmodify();");
}
function main(){
var data= {"fruit":"Apple"};
modify(data);
alert(data.fruit+"\nmain();");
}
main();
Perhaps I misunderstand the passing by reference, but if I'm assigning a value of the object it seems to me that assigning the object the value of a new object should maintain the reference. Could someone explain this behavior to me? Why is the reference lost when assigning a this way?