在 Javascript 中,这个参数是如何通过值而不是通过引用传递的?
我正在努力思考传递参数"的想法.在我正在阅读的一本书中,它指出参数仅按值传递,而不是按引用传递.
I am trying to wrap my head around this idea of 'argument passing.' In a book I am reading it states that arguments are only passed by value not by reference.
function addTen(num) {
num + = 10;
return num;
}
var count = 20;
var result = addTen(count);
alert(count); // 20 - no change
alert(result); // 30
上面的例子很清楚,但下面的例子让我很困惑.
The example above is pretty clear, but the example below leaves me very confused.
当person传递给setName函数时,是不是映射了局部变量'obj'并向下流动函数中的语句?即person首先被设置为属性名称,然后它被分配给一个新的对象,最后这个新创建的人对象被分配属性'Gregg'????
When person is passed to the setName function, doesn't it mirror the local variable 'obj' and flow down the statements in the function? i.e. person is first set to the property name, then it's assigned to a new Object, and finally this new created person object is assigned the property 'Gregg'????
为什么你会得到尼古拉斯"!!!!
Why do you get 'Nicholas'!!!!
function setName(obj) {
obj.name = "Nicholas";
obj = new Object();
obj.name = "Greg";
}
var person = new Object();
setName(person);
alert(person.name); //" Nicholas"
对象被传递给函数作为引用的副本.现在您的示例中会发生什么:
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.