Javascript passing by reference instead of value?
This question already has an answer here:
When you call:
x(a);
A few things are going on. First, the variable a
(which simply holds a reference to an object) is passed by value to the function x
. x
now has its own copy of that reference, which happens to point to the same object in memory. Thus, any changes you make to properties on that referred object will affect other references to said object.
When you call:
this.b = v;
You're again making a copy of v
and setting it to this.b
. Now, a
, v
and this.b
are distinct variables in memory, all storing a reference to the same object.
It seems what you're attempting to do is create a copy of the object itself, so you can manipulate one reference and not affect others. To do so, you'll need to create a completely new object in memory and copy over the properties.
var a = {"x":1}
function x(v) {
this.b = {}; // Create a new object
this.b.x = v.x; // Copy over the x property
// Copy over any other properties too
this.b.x++;
}
x(a);
alert(a.x); // The original object still has an x property of 1
Since this.b
is a new object and we've merely copied over properties from the object referred to by v
, incrementing this.bx
will have no effect on whatever v
is pointing to.
So maybe I can provide you with some clarity by breaking down what's happening.
var a = {"x":1} // a refers to object with key "x"
function x(v) { // v is now a reference to the object with key "x"
this.b = v; // this.b now is a reference to the object with key "x"
this.b.x++; //this.b.x++ points to the object with key "x" so it can increment it's value.
}
x(a); // passes in a the value of reference to object with key "x"
alert(a.x); //... still prints 2
You can do something that could be found in this link:
var o = {};
(function(x){
var obj = Object.create( x );
obj.foo = 'foo';
obj.bar = 'bar';
})(o);
alert( o.foo ); // undefined
链接地址: http://www.djcxy.com/p/20814.html
上一篇: 为什么我的函数在修改数组时修改参数?