问题描述
据我所知,“执行上下文”是由函数的调用位置决定的——而不是函数声明的位置。
因此在下面的示例中,我希望 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
被评估(那个 Dragon 字符串)并作为参数传递给 console.log
。控制台与 this
无关 - 只是输出它的参数。