为什么程序的结果未定义? [英] why the program's result is undefined?

查看:109
本文介绍了为什么程序的结果未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 var foo = {};
 foo.c = foo = {};
 console.log(foo.c);

为什么结果未定义?
i认为它应该是'[object Object]'

why the result is undefined? i thought it is supposed to be '[object Object]'

推荐答案

奇怪的事情发生在作业

foo.c = (foo = {})

foo.c 的github.io/#x8.7\">引用并指向 foo object,在评估内部表达式之前, foo 重新分配 {} emtpy对象文字。所以你的代码相当于

The reference to foo.c is resolved first and points to the old foo object, before the inner expression is evaluated where foo is re-assigned with the {} emtpy object literal. So your code is equivalent to

var foo1 = {};
var foo2 = {};
foo1.c = foo2;
console.log(foo2.c) // obviously undefined now

你也可以尝试

var foo = {}, old = foo;
foo.c = foo = {};
console.log(old, foo, old.c===foo); // {c:{}}, {}, true

这篇关于为什么程序的结果未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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