javascript - 在这些代码中,如何使用执行上下文来解释输出结果?
问题描述
var obj={
say: function(){
console.log(obj); // undefined
}()
};
它终于输出undefined
了。我开始使用执行上下文的知识来解释它,但是我对何时在上下文中创建方法感到怀疑。
我知道进入上下文后,我们首先进入创建阶段,并有一个变量对象,其中包括变量和函数声明。接下来我们进入执行阶段,完成变量和函数的赋值。所以在这个例子中,我们:
首先,进入全局执行上下文的创建阶段,obj
就是undefined
. 接下来,在创建阶段之后,我们进入执行阶段。代码开始执行,obj
现在指向一个对象。但是,在上面的过程中,say
方法是什么时候创建的?在全局执行的创建阶段或执行阶段全球执行?
(如果在创建阶段,那么全局执行上下文的变量对象应该是AO={ obj:undefined,say: referencce to <function>}
)
或者有没有更好的方法来解释为什么这里的结果是undefined
?我在网上搜索,看到有人说这是因为吊装,对吗?
解决方案
It is because you are immediately calling the function without assigning the value of obj. Compare the two scenarios in the bottom snippet:
var obj = {
say: function() {
console.log(obj); // Not undefined since it will run after obj is assigned
}
};
obj.say();
var objUndef = {
say: function() {
console.log(objUndef); // undefined
}() // <--- immediately calling
};
()
), which is running before obj is even assigned. Thus the result is that you log undefined to the console instead of the obj value. If you first create the object and later call its say method using obj.say()
, obj will be defined since you assign obj first before you attempt to call it.
推荐阅读
- json - 嵌套数组,使用 JQ 组合多个过滤器
- javascript - 仅使用密码对用户进行身份验证
- ffmpeg - 音频每隔几秒就断断续续
- php - 使用 Twig 渲染多个页面
- google-apps-script - 如何在 Google Sheets 脚本中为系列中的单个数据点设置颜色
- python - 用逗号格式化一个大整数而不使用 .format()
- ubuntu - start-dfs.sh 抛出端口 22:连接超时错误
- javascript - Bootstrap4 .col 始终占用 100% 并垂直堆叠(引导网格不起作用)
- javascript - 有没有办法使用 vanilla Javascript 或 Jquery 在 DOM 中选择一个 span 类?
- apache-kafka - 是否可以使用 Kafka Connect 将 RDBMS 表镜像到 Kafka 流?