【发布时间】:2021-05-20 20:16:51
【问题描述】:
据我所知,“执行上下文”是由调用函数的位置决定的,而不是声明函数的位置。
因此,在下面的示例中,我希望 this.name 评估为未定义。因此,我不确定console.log() 是如何访问“特许经营”对象内的this 关键字的。
let franchise = {
name: 'How to Train Your Dragon',
allMovies: function() {
console.log(this.name)
},
};
franchise.allMovies() // How to Train Your Dragon
我希望它评估为“未定义”的原因与此示例中的相同:
let franchise = {
name: 'How to Train Your Dragon',
allMovies: function() {
function print() {
return this.name;
}
return print(); //undefined
}
};
【问题讨论】:
-
"所以在下面的示例中,我希望 this.name 的计算结果为 undefined。" 为什么?
-
为问题添加了额外的上下文
-
您的第二个代码返回
undefined,因为print的调用方式,而不是franchise.allMovoes()的调用方式。根据经验,当您使用()执行常规函数时,this的值将变为最后一个.之前的值,因此a.b.c()使用this = a.b执行.c();a.b()执行.b()和this = a;a()执行a()和this = undefined(在草率模式下将替换为全局对象);franchise.allMovies()是a.b()形式,所以this = franchise而print()是a()形式。
标签: javascript this executioncontext