且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Javascript 中,这个参数是如何通过值而不是通过引用传递的?

更新时间: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.