P粉4269063692023-08-22 13:30:26
It’s fun in JavaScript. Consider the following 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 will produce the following output:
10 changed unchanged
obj1
is not a reference at all, then changing obj1.item
has no effect on obj1
outside the function. num
will be 100
, obj2.item
will be "changed"
. Instead, num
remains 10
, and obj2.item
remains "unchanged
". Actually, what happens is that the items passed are passed by value. But the item passed by value itself is a reference. Technically, this is called a shared call.
In practical terms, this means that if you change the parameter itself (such as num
and obj2
), that will not affect the items passed in the parameter. However, if you change the internals of the parameter, that will be propagated back (like obj1
).