Javascript: Object arguments by reference, understanding assignment discrepancy
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(){
开发者_JAVA百科 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?
The question has been asked before (see my comment), but "reference" in this sense isn't the same as the C++ reference, which isn't reassignable.
Assigning a new value to a variable *re*references that variable, rather than changing the previously referenced object.
On the other hand, performing an operation on a variable does affect the referenced object. It's only the assignment operator (and its variants +=
etc) which reassign the variable
精彩评论