Is JavaScript a pass-by-reference or pass-by-value language?
P粉450744515
2023-08-23 18:58:12
<p>Primitive types (numbers, strings, etc.) are passed by value, but objects are unknown since they can all be passed by value (in which case the variable we think holds the object is actually a reference to an object) and pass-by-reference (when we think of an object's variables as holding the object itself). </p>
<p>While it doesn't matter in the end, I'd like to know what is the correct way to present a parameter passing convention. Is there an excerpt from the JavaScript specification that defines the semantics related to this? </p>
JavaScript is fun. Consider this example:
This produces the output:
obj1
is not a reference at all, changingobj1.item
will not have any effect onobj1
outside the function.num
will be100
, andobj2.item
will read"changed"
. Instead,num
remains10
andobj2.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
andobj2
), it will not affect the input to the scope. However, if you change the inner of the parameter, it will propagate upward (same asobj1
).