问题描述
此代码:
var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
您能否解释一下其含义:
Can you please explain what is meant by:
foo.x = foo = {n: 2};
我看到 {n:2}
被分配到 foo
。为什么 undefined
分配给 foo.x
? foo = {n:2};
返回 undefined
?
I see that {n:2}
is assigned to foo
. Why is undefined
assigned to foo.x
? Does foo = {n: 2};
return undefined
?
推荐答案
,即使操作员具有从右到左的优先级,也会首先评估赋值表达式的左侧。因此表达式 foo.x = foo = {n:2}
与 foo.x =(foo = {n:2}相同)
的评估如下:
According to the spec, the left hand side of an assignment expression is evaluated first, even though the operator has right-to-left precedence. Thus the expression foo.x = foo = {n: 2}
which is the same as foo.x = (foo = {n: 2})
is evaluated like this:
- 评估左手表达式
foo.x
获取引用,这是右手表达式的值将被分配到的位置。
- 评估权利-hand expression,以获取将要分配的值。右侧是另一个赋值表达式,因此它的评估方式相同:
- Evaluate the left-hand expression
foo.x
to get a reference, which is where the value of the right-hand expression will be assigned to. - Evaluate the right-hand expression, to to get the value that will be assigned. The right-hand side is another assignment expression, so it gets evaluated the same way:
- 评估
foo
确定分配到何处。 - 评估表达式
{n:2}
,其中创建一个对象,以确定要分配的值。 - 将
{n:2}
分配给foo,并返回{n:2}
。
- Evaluate
foo
to determine where to assign to. - Evaluate the expression
{n:2}
, which creates an object, to determine the value to assign. - Assign
{n:2}
to foo, and return{n:2}
.
{n:2}
),引用为 foo.x
已解决到步骤1( foo
分配了新值)。这与 bar.x
也是一样的,因为之前的行上的赋值 bar = foo
。{n:2}
), to the reference that foo.x
resolved to in step 1 (before foo
was assigned a new value). Which is also the same as bar.x
, because of the assignment bar = foo
on the line before.完成后,原始对象 bar
仍然是对,将有一个 x
属性引用创建的第二个对象。 foo
也是对第二个对象的引用,因此 foo === bar.x
。
When this is done, the original object, that bar
is still a reference to, will have an x
property that references the second object created. foo
is also a reference to that second object, so foo === bar.x
.
这篇关于为什么在foo.x = foo = {n:2}中未定义foo.x的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!