我试图围绕这个“论证传递”的想法。在我正在阅读的一本书中,它指出参数只是通过值传递而不是通过引用传递。
function addTen(num) {
num + = 10;
return num;
}
var count = 20;
var result = addTen(count);
alert(count); // 20 - no change
alert(result); // 30
上面的例子很清楚,但下面的例子让我非常困惑。
当person被传递给setName函数时,它不会镜像局部变量'obj' 并向下流动函数中的语句? 即,首先将人物设置为属性名称,然后将其分配给新的对象,最后为这个新创建的人物对象分配属性“Gregg”????
为什么你会得到'Nicholas'!!!!
function setName(obj) {
obj.name = "Nicholas";
obj = new Object();
obj.name = "Greg";
}
var person = new Object();
setName(person);
alert(person.name); //" Nicholas"
答案 0 :(得分:2)
你得到的是"Nicholas"
,因为JavaScript绝不是“引用”。如果是,您将能够从任何位置更新person
变量。事实并非如此,因此函数中的new Object()
不会改变外部person
变量。
但也不是变量引用对象本身,而是变量包含一种特殊类型的引用,它允许您在不直接访问内存的情况下更新对象。
这就是为什么虽然JavaScript总是“按值”,但你永远不会得到一个对象的完整副本。您只是获得该特殊参考的副本。因此,您可以操纵通过引用副本传递的原始对象,但实际上您无法通过引用替换它。
答案 1 :(得分:2)
传递对象作为参考的副本。现在你的例子中会发生什么:
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
的引用。当您稍后更改局部变量的值时,它不会反映到原始对象。
答案 2 :(得分:2)
所有内容都是JavaScript中的传值。当你传递任何东西作为参数时,JS会复制它并将其发送给函数。传递Object时,JS将该对象的引用复制到另一个变量中,并将该复制的变量传递给该函数。现在,由于传递的变量仍然指向对象,因此可以使用。更改其属性。或[]表示法。但是如果你使用new
来定义一个新对象,那么该变量只指向新的引用。
function setName(obj) {
obj.name = "Nicholas"; // obj pointing to person reference
obj = new Object(); // obj now pointing to another reference
obj.name = "Greg"; // you have changed the new reference not person reference
}
var person = new Object(); // person pointing to person reference
setName(person);
alert( person.name); //" Nicholas"
答案 3 :(得分:1)
参数按值传递,对于对象,表示该值是对象引用的副本。
与进行简单分配时的情况相同,也就是值:
// a variable that contains a reference to an object:
var person = new Object();
// another variable, that gets a reference to the same object:
var people = person;
// a function call with a reference to the object:
setName(person);
在函数中,参数是一个局部变量,它独立于用于将引用发送到函数的变量,但它引用相同的对象:
function setName(obj) {
// as the variable references the original object, it changes the object:
obj.name = "Nicholas";
// now the variable gets a reference to a new object
obj = new Object();
// the new object is changed
obj.name = "Greg";
}
答案 4 :(得分:0)
通过引用传递意味着:
function a(obj) {
obj = 3;
}
var test = new Object();
a(test);
console.log(test); //3, so I have lost the object forever
即。即使是变量赋值也会对调用者可见。
当然,如果目标函数修改了传递给它的对象,那么这些修改 调用者可以看到对象本身。