为什么在foo.x = foo = {n:2}中未定义foo.x的值? [英] Why is the value of foo.x undefined in foo.x = foo = {n: 2}?

查看:163
本文介绍了为什么在foo.x = foo = {n:2}中未定义foo.x的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

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:


  1. 评估左手表达式 foo.x 获取引用,这是右手表达式的值将被分配到的位置。


  2. 评估权利-hand expression,以获取将要分配的值。右侧是另一个赋值表达式,因此它的评估方式相同:



  1. 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.

  2. 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:


  1. 评估 foo 确定分配到何处。

  2. 评估表达式 {n:2} ,其中创建一个对象,以确定要分配的值。

  3. {n:2} 分配给foo,并返回 {n:2}


  1. Evaluate foo to determine where to assign to.
  2. Evaluate the expression {n:2}, which creates an object, to determine the value to assign.
  3. Assign {n:2} to foo, and return {n:2}.


  • 分配值右侧的表达式评估为( {n:2} ),引用为 foo.x 已解决到步骤1( foo 分配了新值)。这与 bar.x 也是一样的,因为之前的行上的赋值 bar = foo

  • Assign the value that the expression on the right-side evaluated to ({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的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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