Is JavaScript a pass-by-reference or pass-by-value language?
This really confuses a lot of people including me. Short answer is: It's always pass by value, even for object. There's no way to alter the value held by a variable passed as a
parameter to function, which would be possible if JS supported passing by reference.
OK, why then when you pass object to function you can change it's members?
Well for objects the value of the variable is a
reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look
like pass by reference. But if you actually change the value of the
object variable you will see that the change does not persist, proving
it's really pass by value.
Example:
Output:function changeObject(x) { x = {member:"bar"}; alert("in changeObject: " + x.member); } function changeMember(x) { x.member = "bar"; alert("in changeMember: " + x.member); } var x = {member:"foo"}; alert("before changeObject: " + x.member); changeObject(x); alert("after changeObject: " + x.member); /* change did not persist */ alert("before changeMember: " + x.member); changeMember(x); alert("after changeMember: " + x.member); /* change persists */
before changeObject: foo in changeObject: bar after changeObject: foo before changeMember: foo in changeMember: bar after changeMember: bar
Няма коментари:
Публикуване на коментар