更新时间:2023-11-12 09:02:58
对象被传递给函数作为引用的副本.现在您的示例中会发生什么:
Objects are passed to function as a copy of the reference. Now what happens in your example is next:
var person = new Object();
function setName(obj) { // a local obj* is created, it contains a copy of the reference to the original person object
obj.name = "Nicholas"; // creates a new property to the original obj, since obj here has a reference to the original obj
obj = new Object(); // assigns a new object to the local obj, obj is not referring to the original obj anymore
obj.name = "Greg"; // creates a new property to the local obj
}
setName(person);
alert( person.name); //" Nicholas"
*
= obj
是一个局部变量,包含一个值,它是对原始对象代码>.当您稍后更改局部变量的值时,它不会反映到原始对象.
*
= obj
is a local variable containing a value, which is a reference to the original obj
. When you later change the value of the local variable, it's not reflecting to the original object.