本文介绍了为什么这样做? 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中的对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:06