Are parameters passed in JavaScript by value or by reference?
P粉394812277
2023-08-21 15:57:16
<p>Primitive types (numbers, strings, etc.) are passed by value, but objects are unknown since they can both be passed by value (in which case we think the variable holding the object is actually the object reference), can also be passed by reference (in which case we consider the variable to hold the object itself). </p>
<p>While it ultimately doesn't matter, I'd like to know how to render the parameter passing convention correctly. Is there an excerpt from the JavaScript specification that defines what the semantics about this should be? </p>
It’s fun in JavaScript. Consider the following example:
This will produce the following output:
obj1
is not a reference at all, then changingobj1.item
has no effect onobj1
outside the function.num
will be100
,obj2.item
will be"changed"
. Instead,num
remains10
, andobj2.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
andobj2
), that will not affect the items passed in the parameter. However, if you change the internals of the parameter, that will be propagated back (likeobj1
).