It's interesting in JavaScript.(JavaScript很有趣。)
Consider this example:(考虑以下示例:)
function changeStuff(a, b, c) { a = a * 10; b.item = "changed"; c = {item: "changed"}; } var num = 10; var obj1 = {item: "unchanged"}; var obj2 = {item: "unchanged"}; changeStuff(num, obj1, obj2); console.log(num); console.log(obj1.item); console.log(obj2.item);
This produces the output:(产生输出:)
10
changed
unchanged
- If
obj1
was not a reference at all, then changing obj1.item
would have no effect on the obj1
outside of the function.(如果obj1
根本不是引用,则更改obj1.item
将对该函数外部的obj1
无效。)
- If the argument was a proper reference, then everything would have changed.(如果该论点是适当的参考,那么一切都会改变。)
num
would be 100
, and obj2.item
would read "changed"
.(num
为100
,而obj2.item
读为"changed"
。)
Instead, the situation is that the item passed in is passed by value.(相反,情况是传入的项目是按值传递的。)
But the item that is passed by value is itself a reference.(但是,按值传递的项目本身就是参考。) Technically, this is called call-by-sharing .(从技术上讲,这称为共享呼叫 。)
In practical terms, this means that if you change the parameter itself (as with num
and obj2
), that won't affect the item that was fed into the parameter.(实际上,这意味着如果您更改参数本身(如num
和obj2
),则不会影响输入该参数的项目。)
But if you change the INTERNALS of the parameter, that will propagate back up (as with obj1
).(但是,如果您更改参数的INTERNALS ,则它将传播回去(与obj1
)。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…