Monday, May 20, 2024
74
rated 0 times [  81] [ 7]  / answers: 1 / hits: 18001  / 13 Years ago, fri, february 24, 2012, 12:00:00

I know that in JS, objects are passed by reference, for example:



function test(obj) {
obj.name = 'new name';
}

var my_obj = { name: 'foo' };
test(my_obj);
alert(my_obj.name); // new name


But why doesn't the below work:



function test(obj) {
obj = {};
}

var my_obj = { name: 'foo' };
test(my_obj);
alert(my_obj.name); // foo


I have set the object to {} (empty) but it still says foo.



Can any one explain the logic behind this?


More From » pass-by-reference

 Answers
24

If you are familiar with pointers, that's an analogy you can take. You're actually passing a pointer, so obj.someProperty would dereference to that property and actually override that, while merely overriding obj would kill off the pointer and not overwrite the object.


[#87223] Thursday, February 23, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;