Javascript对引用与值定义的变量的混淆 [英] Javascript confusion over variables defined by reference vs value

查看:42
本文介绍了Javascript对引用与值定义的变量的混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 javascript 语言的以下属性:

I understand the following property of the javascript language:

var bar = 1;
var foo = bar;
bar = "something entirely different";
// foo is still 1

但是,当尝试将此逻辑应用于对象时,它的行为似乎有所不同:

However, when trying to apply this logic to an object it seems to act differently:

var bar = {};
bar.prop = 1;
var foo = bar;
bar.prop = "something entirely different";
// foo.prop now changes to "something entirely different"
// but...
bar = "no longer an object";
// now foo remains an object with the prop property

有人能告诉我发生了什么以及为什么会有所不同吗?

Can someone tell me what's happening and why there is a difference?

推荐答案

没错.当您将变量分配给一个对象时,您实际上是在创建对该对象的第二个引用.在第一种情况下,您所做的是分配 bar 指向 foo 指向的字符串,但随后您更改 bar 指向您重新分配 bar 的时间.

That's correct. When you assign a variable to an object, you're really creating a second reference to that object. In the first case, what you're doing is assigning bar to point at the string foo points to, but then you change what bar points to when you reassign bar.

在第二个示例中,您将 bar 分配给一个新对象,然后将 foo 指向同一对象,然后重新分配 bar到一个字符串.foo 仍然指向同一个对象.

In the second example, you assign bar to a new object, then you point foo at that same object, then you reassign bar to a string. foo is still pointed at the same object.

这样想:bar = "something"改变 bar 指向的内容,而不是改变实际的对象 {} 到字符串.

Think of it like this: bar = "something" is changing what bar points to, not changing the actual object {} to a string.

这篇文章很好地解释了您所看到的内容.不过,我正在寻找更好/更权威的参考资料.

This article is a fairly good explanation of what you're seeing. I'm looking for even better / more authoritative references, however.

这篇关于Javascript对引用与值定义的变量的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆