求解释,为何a.x为undefined?

var a = {n: 1};
var b = a;
a.x = a = {n: 2};

console.log(b.x) // {n:2}
console.log(a.x) // undefined

阅读 1.6k
2 个回答

点的优先级高于=
a.x = a = {n: 2} 这个等式中,将a.x取出 a.x指向一个内存
然后从右向左开始赋值 a = {n:2} a.x = a

assignment expression/evalution:

  1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then

    1. Let lref be the result of evaluating LeftHandSideExpression.
    2. ReturnIfAbrupt(lref).
    3. If IsAnonymousFunctionDefinition(AssignmentExpression) and IsIdentifierRef of LeftHandSideExpression are both true, then

      1. Let rval be the result of performing NamedEvaluation for AssignmentExpression with argument GetReferencedName(lref).
    4. Else,

      1. Let rref be the result of evaluating AssignmentExpression.
    5. Let rval be ? GetValue(rref).
    6. Perform ? PutValue(lref, rval).
    7. Return rval.

......

赋值左侧先求值(1.1), 此时 a.x 求值结果为 b.x (此时 a 就是 b ;此后 a 的改变不影响这一结果)。

然后右侧求值(1.4.1),求值过程中 a 被改变了,变成了 {n:2} 。此后 ab 不在是同一对象。
右侧求值的结果是 {n:2}

最后,右侧求值的结果被赋值给左侧(1.6)。b.x 变为 {n:2}a{n:2}a.xundefined

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题