所以我有这段代码,我试图通过将它作为对函数的引用来改变对象:
var c = { why: 'older' };
var d;
d = c;
//passing by reference
function changeGreeting(obj) {
obj.why = 'newer' ; // mutate
}
changeGreeting(d)
console.log(c);
console.log(d);
然后我让邪恶的双胞胎代码看起来一样但不表现:
var c = { why: 'older' };
var d;
d = c;
//passing by reference, i wish..
function changeGreeting(obj) {
obj = { why: 'newer' }; // trying to mutate..
}
changeGreeting(d)
console.log(c);
console.log(d);
答案 0 :(得分:3)
此代码obj = { why: 'newer' };
不会发生变异,它只会分配给函数内的局部变量obj
。
要改变对象,您需要使用属性赋值。
换句话说,obj
指向某个对象(包含对该对象的引用),因此您可以对其进行变异。通过将值重新分配给其他对象,您将参考新对象替换对原始对象的引用。
答案 1 :(得分:2)
您的功能基本上表现如下
function changeGreeting(obj) {
var obj; // creates the local variable
obj = d; // assign the arguments (objects are passed by reference)
obj = { why: 'newer' }; // Creates new reference for local object
}
由于上述行为,c
和d
的引用将被保留,并在函数调用之前继续指向相同的内存位置。
修改强>
第一个场景的行为类似于以下
function changeGreeting(obj) {
var obj; // creates the local variable
obj = d; // assign the arguments (objects are passed by reference)
obj.why = 'newer'; // Updates local variable obj which has same reference as "d" and "c"
}
答案 2 :(得分:1)
当你这样做的时候
obj = { why: 'newer' };
您正在将函数范围变量obj
修改为对新对象{ why: 'newer' }
的引用。