JavaScript function arguments store by reference
This question already has an answer here:
The real problem here is that you're not mutating anything; you're just reassigning the variable z
in the function. It wouldn't make a difference if you passed an object or array.
var x = ['test'];
var y = function(z) {
z=['foo'];
return z;
}
y(x);
x; // Still ['test']
Now, what others have said is also true. Primitives cannot be mutated . This is actually more interesting than it sounds, because the following code works:
> var x = 1;
> x.foo = 'bar';
"bar"
> x
1
> x.foo
undefined
Notice how the assignment to x.foo
was seemingly successful, yet x.foo
is nowhere to be found. That's because JavaScript readily coerces primitive types and object types (there are "object" versions of primitives, that are normal objects). In this case, the primitive 1
is being coerced into a new object ( new Number(1)
), whose foo
attribute is getting set, and then it is promptly destroyed, so no lasting effects occur.
Thanks to @TeddHopp about this note:
Only the value is passed for all variables, not just primitives. You cannot change a variable in the calling code by passing it to a function. (Granted, you can change the object or array that may be passed; however, the variable itself remains unchanged in the calling code.)
If you want the value of x
to change anyways you can do:
x = y(x);
链接地址: http://www.djcxy.com/p/20978.html
上一篇: 使用Javascript分配对象:浅层还是深层复制?
下一篇: JavaScript函数参数通过引用存储