我的两分钱.... JavaScript 是否通过引用或值传递参数无关紧要。真正重要的是分配与变异。
我写了更长的,more detailed explanation in this link。
当您传递任何东西(无论是对象还是原始数据)时,JavaScript 所做的只是在函数内部分配一个新变量...就像使用等号 (=)。
该参数在函数内的行为与您刚刚使用等号分配一个新变量时的行为完全相同......举这些简单的例子。
var myString = 'Test string 1';
// Assignment - A link to the same place as myString
var sameString = myString;
// If I change sameString, it will not modify myString,
// it just re-assigns it to a whole new string
sameString = 'New string';
console.log(myString); // Logs 'Test string 1';
console.log(sameString); // Logs 'New string';
如果我将myString 作为参数传递给函数,它的行为就像我只是将它分配给一个新变量一样。现在,让我们做同样的事情,但使用函数而不是简单的赋值
function myFunc(sameString) {
// Reassignment... Again, it will not modify myString
sameString = 'New string';
}
var myString = 'Test string 1';
// This behaves the same as if we said sameString = myString
myFunc(myString);
console.log(myString); // Again, logs 'Test string 1';
在将对象传递给函数时可以修改对象的唯一原因是因为您没有重新分配...相反,可以更改或变异对象...再次,它的工作方式相同。
var myObject = { name: 'Joe'; }
// Assignment - We simply link to the same object
var sameObject = myObject;
// This time, we can mutate it. So a change to myObject affects sameObject and visa versa
myObject.name = 'Jack';
console.log(sameObject.name); // Logs 'Jack'
sameObject.name = 'Jill';
console.log(myObject.name); // Logs 'Jill'
// If we re-assign it, the link is lost
sameObject = { name: 'Howard' };
console.log(myObject.name); // Logs 'Jill'
如果我将myObject 作为参数传递给函数,它的行为就像我只是将它分配给一个新变量一样。同样,具有完全相同的行为但具有功能的相同事物。
function myFunc(sameObject) {
// We mutate the object, so the myObject gets the change too... just like before.
sameObject.name = 'Jill';
// But, if we re-assign it, the link is lost
sameObject = {
name: 'Howard'
};
}
var myObject = {
name: 'Joe'
};
// This behaves the same as if we said sameObject = myObject;
myFunc(myObject);
console.log(myObject.name); // Logs 'Jill'
每次将变量传递给函数时,您都在“分配”参数的名称,就像使用等号 = 一样。
永远记住等号= 表示赋值。
将参数传递给函数也意味着赋值。
它们是相同的,并且两个变量的连接方式完全相同。
修改变量影响不同变量的唯一时间是底层对象发生变异时。
区分对象和基元没有意义,因为它的工作方式与您没有函数并只是使用等号分配新变量的方式完全相同。