通过引用传递对象的函数,意外行为

时间:2018-04-13 11:04:12

标签: javascript function pass-by-reference javascript-objects

所以我有这段代码,我试图通过将它作为对函数的引用来改变对象:

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);

这成功变异并按预期输出: enter image description here 到目前为止没有问题..

然后我让邪恶的双胞胎代码看起来一样但不表现:

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);

我希望这可以以相同的方式工作,但它没有(它没有变异)。 enter image description here 寻找一个很清楚的解释原因?

3 个答案:

答案 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        
}

由于上述行为,cd的引用将被保留,并在函数调用之前继续指向相同的内存位置。

修改

第一个场景的行为类似于以下

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' }的引用。