问题描述
我对变量分配有疑问
var foo = {n: 1};
foo.x = foo = {n: 2};
console.log(foo.x) // undefined
为什么foo.x
是undefined
?
推荐答案
=
赋值运算符是右关联的,这意味着赋值链是从右到左求值的.也就是说,语言会这样对待
The =
assignment operator is right-associative, meaning that a chain of assignments is evaluated right to left. That is, the language treats this
x = y = x+2;
好像是写的
x = (y = x+2);
因此,首先为y
分配加法结果(5
),然后为x
分配该赋值的值,该值也为5
.
So first y
is assigned the result of the addition (5
), and then x
is assigned the value of that assignment, which is also 5
.
问题中的第一个例子是同一个故事,但事情要复杂一些:
The first example in your question is the same story, but things are a little more complicated:
foo.x = foo = { n: 2 };
首先进行的是对象文字的foo
分配.但是,在此之前, 语言将确定foo.x
的引用值,该引用值是对原始上的(尚不存在)属性的引用. c7>对象.因此,当对该属性进行右手赋值时,它确实起作用,但是该属性是在旧对象上设置的,而不是在新对象上设置的!
The first assignment that's made is to foo
, of that object literal. However, before that point, the language will have determined the reference value of foo.x
, which is a reference to a (not-yet existing) property on the original foo
object. Thus, when the value of the right-hand assignment is made to that property, it does work, but the property is set on the old object, not the new one!
让我们更改示例:
var foo = {n: 1}, foo2 = foo;
foo.x = foo = {n: 2};
console.log(foo2.x); // { n: 2 }
该版本保留了对变量foo2
中foo
原始值的另一个引用.即使foo
在双重分配中被覆盖,foo2
仍将继续引用原始的foo
.
That version preserves another reference to the original value of foo
in the variable foo2
. Even though foo
is overwritten in the double assignment, foo2
will continue to refer to the original foo
.
这篇关于解释此javascript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!