为什么console.log(obj.prop = value),输出 value

const obj = {};
console.log(obj.name = 'hello');// 为什么这个地方输出 hello

备注,其实很少会这样使用,只是在看ts中定义枚举的时候看到了类似的代码,所以理解所以提出来看看

阅读 2k
3 个回答

首先,参考一下ECMA对赋值运算的定义:

The production AssignmentExpression : LeftHandSideExpression = AssignmentExpression is evaluated as follows:

1.Let lref be the result of evaluating LeftHandSideExpression.
2.Let rref be the result of evaluating AssignmentExpression.
3.Let rval be GetValue(rref).
4.Throw a SyntaxError exception if the following conditions are all true:

  • Type(lref) is Reference is true
  • IsStrictReference(lref) is true
  • Type(GetBase(lref)) is Environment Record
  • GetReferencedName(lref) is either "eval" or "arguments"

5.Call PutValue(lref, rval).
6.Return rval.

所以说,obj.name = 'hello'这个表达示最后return 'hello'.
从内存角度分析。执行这个表达式的时候,开辟一块内存,放置hello,obj这个对象的一个属性name指向这块内存。执行完这个表达式后,返回了hello这个内存的地址。
最后console.log()的时候就打印出了指向内存地址的值。

赋值表达式的返回值就是右值。(也存在 this 丢失问题。

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