什么时候通过引用而不是按值复制JavaScript值有经验法则吗?
即使作为一个有点经验丰富的JS开发人员,我发现自己经常对浅层和深层对象副本感到惊讶。
Even as a somewhat seasoned JS dev I find myself constantly suprised at shallow vs. deep copies of objects.
当JavaScript值是什么时,是否有任何经验法则通过引用复制而不是主要对象类型的值?例如,我知道字符串值总是按值而不是引用复制。
Are there any rules of thumb for when JavaScript values are copied by reference and not by value for the major object types? For example, I know string values are always copied by value not reference.
在JavaScript中,所有对象都存储并通过引用传递。
In JavaScript, all objects are stored and passed 'by reference'.
var a = { v: 'a' }, b = { v: 'b' };
a=b;
b.v='c';
a
和 b
将引用同一个对象; av =='c'
和 bv =='c'
。
a
and b
will reference the same object; a.v == 'c'
and b.v == 'c'
.
原始数据类型(字符串
,数字
,布尔值
, null
, undefined
)是不可变的;它们按值传递。
Primitive datatypes (string
, number
, boolean
, null
, and undefined
) are immutable; they are passed by value.
var a = 'a', b = 'b';
a=b;
b='c';
由于我们正在处理基元, a =='b'
和 b =='c'
。
Since we're dealing with primitives, a == 'b'
and b == 'c'
.
Pedants会告诉你JavaScript在传统意义上不是传递引用,或者它是一种纯粹的传值语言,但我认为这样做会使实际目的复杂化。不,你不能直接修改传递给函数的参数,就好像它是一个变量(如果语言是真正的传递引用就是真的),但是你也没有收到副本作为参数传递的对象(如果它是真值pass-by-value那样)。对于大多数用途(从语言用户的角度来看),传递给函数的对象是引用,因为您可以修改该对象并影响调用者的对象。另请参阅此问题的精彩答案。
Pedants will tell you that JavaScript isn't pass-by-reference in a classical sense, or that it's a "pure pass-by-value" language, but I think that complicates things for practical purposes. No, you can't directly modify an argument passed to a function as if it were a variable (which would be true if the language were true pass-by-reference), but you also don't receive a copy of an object passed as an argument (as you would if it were true pass-by-value). For most purposes (from the standpoint of the language's user, you), objects passed to a function are references, since you can modify that object and it affects the caller's object. See also the fantastic answers to this question.