Javascript代码技巧:foo.x的价值是什么 [英] Javascript code trick :What's the value of foo.x
问题描述
我在Github前端采访问题集中遇到了这个问题:
I met this problem in 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};
声明一个对象foo
,其属性n
等于1 。 -
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 objectfoo
which has propertyn
equal to 1.var bar = foo;
declared an objectbar
which refer to same object asfoo
.foo.x = foo = {n: 2};
which I believe is equal tofoo.x = (foo = {n: 2});
- And then I got
foo.x
equals toundefined
. However, the value ofbar.x
is the object{n:2}
.
如果 bar
和 foo
引用同一个对象,为什么 bar.x
获得价值,而 foo.x
是未定义
? foo.x = foo = {n:2};
?
If bar
and foo
refer to same object, why bar.x
got value while foo.x
is undefined
? What is really happening in foo.x = foo = {n: 2};
?
推荐答案
foo.x = foo = {n: 2};
确定 foo.x
是指a属性 x
{n:1}
对象,指定 {n:2}
到 foo
,并指定新值 foo
- { n:2}
- 到 {n:1}
对象的属性 x
。
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
foo.x
指的是在 foo
更改之前确定的。
The important thing is that the foo
that foo.x
refers to is determined before foo
changes.
参见 ES5规范第11.13.1节:
-
让 lref 成为评估 LeftHandSideExpression 的结果。
让 rref 成为评估 AssignmentExpression 的结果。
赋值运算符从右到左关联,因此得到:
The assignment operator associates right to left, so you get:
foo.x = (foo = {n: 2})
左手边在右手边评估。
这篇关于Javascript代码技巧:foo.x的价值是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!