通过引用函数传递对象,意外行为
Passing an object by reference to a function, unexpected behaviour
所以我有这段代码,我试图通过将对象作为对函数的引用来传递它来改变对象:
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);
我希望它能以同样的方式工作,但它没有(它无法变异)。
正在寻找一个清楚的解释为什么?
此代码 obj = { why: 'newer' };
不会发生变化,它只是分配给函数内的局部变量 obj
。
要改变对象,您需要使用属性赋值。
换句话说,obj
指向某个对象(包含对该对象的引用),因此您可以改变它。通过将值重新分配给其他对象,您正在将对原始对象的引用替换为对新对象的引用。
当你这样做的时候
obj = { why: 'newer' };
您正在将函数作用域变量 obj
修改为对新对象 { why: 'newer' }
.
的引用
你的函数基本上表现如下
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"
}
所以我有这段代码,我试图通过将对象作为对函数的引用来传递它来改变对象:
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);
我希望它能以同样的方式工作,但它没有(它无法变异)。
此代码 obj = { why: 'newer' };
不会发生变化,它只是分配给函数内的局部变量 obj
。
要改变对象,您需要使用属性赋值。
换句话说,obj
指向某个对象(包含对该对象的引用),因此您可以改变它。通过将值重新分配给其他对象,您正在将对原始对象的引用替换为对新对象的引用。
当你这样做的时候
obj = { why: 'newer' };
您正在将函数作用域变量 obj
修改为对新对象 { why: 'newer' }
.
你的函数基本上表现如下
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"
}