[英]JavaScript objects as property of object reference
I want to understand how objects work in JS.我想了解对象在 JS 中是如何工作的。
const obj = { inner: { a: 'Hello' } };
const clone = { ...obj };
// obj === clone -> false
// !!! BUT !!!
// obj.inner === clone.inner -> true
clone.inner = { a: 'world' };
// obj === { inner: { a: 'Hello' } }
// clone === { inner: { a: 'World' } }
Is there a documentation on this behaviour?是否有关于这种行为的文档? Can I rely on inner objects references equality while creating new object via spread operator?
通过扩展运算符创建新的 object 时,我可以依赖内部对象引用相等吗?
...
spread syntax
creates a shallow copy anything deeper then level one will still stays as reference to original object ...
spread syntax
创建一个浅拷贝任何更深的东西,然后一级仍将作为对原始 object 的参考
const obj = { inner: { a: 'Hello' } }; const clone = {...obj }; console.log(obj === clone) console.log(obj.inner === clone.inner)
Shallow Cloning If the item being spread into the target is an object, only a reference to that object will be copied.浅层克隆 如果传播到目标中的项目是 object,则只会复制对该 object 的引用。 The spread operator will not recursively deep clone properties.
扩展运算符不会递归地深度克隆属性。 In addition, only own, enumerable properties are copied.
此外,只复制自己的、可枚举的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.