P粉2311124372023-08-24 14:43:30
JavaScript is fun. 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
obj1
is not a reference at all, changing obj1.item
will not have any effect on obj1
outside the function. num
will be 100
, and obj2.item
will read "changed"
. Instead, num
remains 10
and obj2.item
remains "unchanged
". Instead, the situation is that the incoming item is passed by value. But an item passed by value is itself a reference. Technically, this is called a shared call.
In practical terms, this means that if you change the parameters themselves (such as num
and obj2
), it will not affect the input to the scope. However, if you change the inner of the parameter, it will propagate upward (same as obj1
).