JavaScript代码技巧:foo.x的值是什么 [英] JavaScript code trick: What's the value of foo.x

查看:61
本文介绍了JavaScript代码技巧:foo.x的值是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在GitHub前端面试问题集中发现了这个问题:

I found this problem in a GitHub front-end interview questions collection:

var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};

问题:foo.x的值是什么?

Question: What is the value of foo.x?

答案是undefined.

我已经做过一些研究,并且我了解这个问题(如果我错了,请纠正我):

I've done some research and what I understand this problem is (correct me if I'm wrong):

  • var foo = {n: 1};声明具有属性n等于1的对象foo.
  • var bar = foo;声明一个对象bar,该对象引用与foo相同的对象.
  • 我相信
  • foo.x = foo = {n: 2};等于foo.x = (foo = {n: 2});
  • 然后我得到foo.x等于undefined.但是,bar.x的值是对象{n:2}.
  • var foo = {n: 1}; declares an object foo which has property n equal to 1.
  • var bar = foo; declares an object bar which refers to the same object as foo.
  • foo.x = foo = {n: 2}; which I believe is equal to foo.x = (foo = {n: 2});
  • And then I got foo.x equals to undefined. However, the value of bar.x is the object {n:2}.

如果barfoo引用相同的对象,为什么bar.xfoo.xundefined时得到一个值? foo.x = foo = {n: 2};中到底发生了什么?

If bar and foo refer to same object, why did bar.x get a value while foo.x is undefined? What is really happening in foo.x = foo = {n: 2};?

推荐答案

foo.x = foo = {n: 2};

确定foo.x引用{n: 1}对象的属性x,将{n: 2}分配给foo,并将新值foo{n: 2} –分配给属性 {n: 1}对象.

determines that foo.x refers to a property x of the {n: 1} object, assigns {n: 2} to foo, and assigns the new value of foo{n: 2} – to the property x of the {n: 1} object.

重要的是,foo.x所引用的foo是在foo更改之前确定的.

The important thing is that the foo that foo.x refers to is determined before foo changes.

请参见 ES5规范的11.13.1节:

  1. lref 成为评估 LeftHandSideExpression 的结果.

  1. Let lref be the result of evaluating LeftHandSideExpression.

rref 成为评估 AssignmentExpression 的结果.

赋值运算符从右到左关联,所以您得到:

The assignment operator associates right to left, so you get:

foo.x = (foo = {n: 2})

首先评估左侧,然后评估右侧.

The left hand side is evaluated before the right hand side.

这篇关于JavaScript代码技巧:foo.x的值是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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