这会复制对象还是添加对它的引用?
假设我有以下对象:
var lol = {
section: {},
other: {foo: 'bar', foob: 'baz'}
};
现在,如果我执行以下操作:
lol.section.other = lol.other;
将引用 section.other
链接到 other
还是整个 other 对象是否被复制并放置在
section
中?
Let's say I have the following object:
var lol = {
section: {},
other: {foo: 'bar', foob: 'baz'}
};
Now if I do the following:
lol.section.other = lol.other;
will a reference be made linking section.other
to other
or will the entire other
object be copied and placed in section
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在创建对同一对象的两个引用。
Javascript 对象永远不会被隐式复制。
You're creating two references to the same object.
Javascript objects are never implicitly copied.
与许多其他面向对象语言一样,JavaScript 也通过引用传递和分配对象,因此,您只是创建对现有对象的新引用。
JavaScript 与其他面向对象语言的区别在于继承和封装。所以在这些领域要小心。
Like quite a few other OO languages, JavaScript also passes and assigns the object by reference therefore, you are only creating a new reference to an existing object.
Where JavaScript breaks away from other OO languages is in inheritance and in encapsulation. So be cautious in those areas.
正如 SLaks 所说,javascript 将对象分配为引用(不复制)。很容易测试或自己查看:
您可以在这里看到它: http://jsfiddle.net/jfriend00/r73LH/ 。
As SLaks said, javascript assigns objects as a reference (without copying). It's easy to test or see yourself:
You can see it here: http://jsfiddle.net/jfriend00/r73LH/.