为什么在foo.x = foo = {n:2}中未定义foo.x的值?

编程入门 行业动态 更新时间:2024-10-26 17:22:18
本文介绍了为什么在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:

  • 评估左手表达式 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 。
  • 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的值?

    本文发布于:2023-10-16 15:55:26,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1498039.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:中未   定义   foo

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!