基本类型(数字、字符串等)是通过值传递的,但对象是未知的,因为它们既可以是通过值传递的(如果我们认为保存对象的变量实际上是对该对象的引用),也可以是通过引用传递的(当我们认为对象的变量包含对象本身时)。
虽然这在最后并不重要,但我想知道表示传递约定的参数的正确方式是什么。有没有JavaScript规范的摘录,它定义了关于这一点的语义?
发布于 2009-02-05 21:37:35
该变量并不“持有”对象;它持有一个引用。您可以将该引用赋给另一个变量,现在两者都引用同一个对象。它总是通过值传递(即使值是引用...)。
没有办法改变作为参数传递的变量所持有的值,如果JavaScript支持按引用传递,这是可能的。
发布于 2011-06-03 07:04:31
函数外部的对象通过提供对外部对象的引用传递到函数中。
当您使用该引用来操作其对象时,外部的对象会因此受到影响。但是,如果在函数内部决定将引用指向其他对象,则根本不会影响外部对象,因为您所做的只是将引用重定向到其他对象。
发布于 2015-02-13 19:00:25
可以这样想:它总是通过值传递。但是,对象的值不是对象本身,而是对该对象的引用。
下面是一个示例,传递一个数字(原语类型)
function changePrimitive(val) {
// At this point there are two '10's in memory.
// Changing one won't affect the other
val = val * 10;
}
var x = 10;
changePrimitive(x);
// x === 10
对对象重复此操作会产生不同的结果:
function changeObject(obj) {
// At this point there are two references (x and obj) in memory,
// but these both point to the same object.
// changing the object will change the underlying object that
// x and obj both hold a reference to.
obj.val = obj.val * 10;
}
var x = { val: 10 };
changeObject(x);
// x === { val: 100 }
再举一个例子:
function changeObject(obj) {
// Again there are two references (x and obj) in memory,
// these both point to the same object.
// now we create a completely new object and assign it.
// obj's reference now points to the new object.
// x's reference doesn't change.
obj = { val: 100 };
}
var x = { val: 10 };
changeObject(x);
// x === { val: 10}
https://stackoverflow.com/questions/518000
复制相似问题