这会复制对象还是添加对它的引用?

发布于 2024-12-06 14:17:54 字数 324 浏览 2 评论 0原文

假设我有以下对象:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

暖风昔人 2024-12-13 14:17:54

您正在创建对同一对象的两个引用。

Javascript 对象永远不会被隐式复制。

You're creating two references to the same object.

Javascript objects are never implicitly copied.

↘紸啶 2024-12-13 14:17:54

与许多其他面向对象语言一样,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.

以可爱出名 2024-12-13 14:17:54

正如 SLaks 所说,javascript 将对象分配为引用(不复制)。很容易测试或自己查看:

var lol = {
    section: {},
    other: {foo: 'bar', foob: 'baz'}
};

lol.section.other = lol.other;

lol.other.foo = 'test';
console.log(lol.section.other.foo);   // will be 'test', not 'bar'

您可以在这里看到它: http://jsfiddle.net/jfriend00/r73LH/

As SLaks said, javascript assigns objects as a reference (without copying). It's easy to test or see yourself:

var lol = {
    section: {},
    other: {foo: 'bar', foob: 'baz'}
};

lol.section.other = lol.other;

lol.other.foo = 'test';
console.log(lol.section.other.foo);   // will be 'test', not 'bar'

You can see it here: http://jsfiddle.net/jfriend00/r73LH/.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文