简体   繁体   English

Javascript object 文字分配和参考如何工作?

[英]How Javascript object literal assignment and reference works?

I have a simple question我有一个简单的问题

let obj1 = {};
obj2= obj1;`

Here obj1 and obj2 are referencing the same object in the memory ie obj1===obj2 --> true .这里 obj1 和 obj2 在 memory 中引用相同的 object 即obj1===obj2 --> true So by this logic any operation on obj2 will affect obj1.所以按照这个逻辑,对 obj2 的任何操作都会影响 obj1。

Now if I assign a property to obj2现在,如果我将属性分配给 obj2

 let obj1 = {}; obj2 = obj1; obj2['a'] = {}; obj2 = obj2['a']; // why this operation didn't change obj1, if they are referencing the same object? console.log(obj1); // -- > { a: {} }; console.log(obj2); // -- > {};

now obj1===obj2 --> false why is this?现在obj1===obj2 --> false为什么会这样?

Also How come obj2 = {} is different then obj2 = obj2['a'] ?另外obj2 = {} is different then obj2 = obj2['a']

A screenshot for clarifying myself澄清自己的截图

在此处输入图像描述

Thanks for your help in advance.提前感谢您的帮助。

For objects, the assignment operator = assigns a reference to the object.对于对象,赋值运算符=分配对 object 的引用。

So in:所以在:

let obj1 = {};
let obj2 = obj1;

both obj1 and obj2 reference the same object. obj1obj2都引用相同的 object。 Now:现在:

obj2['a'] = {};

creates a new property a and assigns it a value that is a reference to a new object.创建一个新属性a并为其分配一个值,该值是对新 object 的引用。 Since both obj1 and obj2 reference the same object, you'll also find:由于obj1obj2都引用相同的 object,您还会发现:

obj2.a === obj1.a

But then:但是之后:

obj2 = obj2['a']; // why this operation didn't change obj1, if they are referencing the same object ?

You've now assigned a different object to obj2 , so it now references the new object initially assigned to obj2.a and:您现在已将不同的 object 分配给obj2 ,因此它现在引用最初分配给obj2.a并且:

obj1.a === obj2;

So obj1 was modified (or more correctly, the object referenced by obj1 was modified).所以obj1被修改了(或者更准确地说, obj1引用的 object 被修改了)。

Some code:一些代码:

 // obj1 and obj2 reference the same object let obj1 = {}; let obj2 = obj1; console.log('obj2 === obj1 ' + (obj2 === obj1)); // true // Assign new object to obj2.a obj2['a'] = {}; // Affects obj1 console.log('obj2.a === obj1.a ' + (obj2.a === obj1.a)); // true // Assign new object to obj2 obj2 = obj2['a']; // obj2 now references a different object to obj1 console.log('obj1 === obj2 ' + (obj1 === obj2)); // false // obj1.a still references new object console.log('obj1.a === obj2 ' + (obj1.a === obj2)); // true

obj2 is an object, obj2[a] is another object. obj2 是一个 object,obj2[a] 是另一个 object。 The result of comparing two objects is false.比较两个对象的结果是错误的。

 {} === {}    // false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM