为什么这样做? Javascript中的对象引用 [英] Why does this work? Object references in Javascript
问题描述
我终于好奇地发现为什么javascript会运用它的巫术魔法来了解为什么不能创建所有对象引用。
I've finally been curious enough to find out why javascript does its voodoo magic to learn why not all object references are created equal.
给出示例:
var a, b, c, d;
a = 100; b = a;
c = {}; d = c;
b = 10; d.e = 'f';
console.log(a, b); // outputs 100, 10
console.log(c, d); // outputs object => e = 'f', object => e = 'f'
如果javascript中的所有变量都是对象,那么用例 c
和 d
显式转换为对象
与定义不同 a
和 b
as Number
?或者,为什么 c
和 d
会彼此链接,而不是 a
和 b
?
If all variables in javascript are objects, then what makes the use case with c
and d
cast explicitly as an Object
so different than defining a
and b
as Number
? Or, why will c
and d
be linked to one another, and not a
and b
?
推荐答案
JavaScript中的所有变量不是对象。还有原生类型。
All variables in JavaScript are not objects. There are native types as well.
c
和 d
没有链接彼此。它们指向同一个对象引用。如果您将 d
重新分配给其他内容,则不会影响 c
。
c
and d
are not linked to one another. They are pointing to the same object reference. If you were to reassign d
to something else, it will not affect c
.
var c = {};
var d = c;
d = { foo: "bar" };
c === d // false
但是,如果你去的话修改 c
或 d
引用的对象,它将修改同一个对象,因为 c
和 d
都指示与示例中相同的对象。
However, if you were to modify the object being referenced by c
or d
, it will modify the same object since c
and d
are both referring to the same object as in your example.
这篇关于为什么这样做? Javascript中的对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!