【发布时间】:2024-01-02 13:18:01
【问题描述】:
我知道this 关键字总是指当前作用域的this,只要你在function() { ... } 中包装一些东西,它就会改变。我的问题是,为什么我可以在setTimeout函数内部的函数中访问外部作用域变量x?
var x = 45;
function getRecipe(recipe) {
x = 35;
return {
displayRecipe: function(a) {
//here we have access to x=35
setTimeout(function() {
//why do we have access to x=35 and to recipe here?
console.log(this.x + a + recipe);
}, 1500)
}
}
}
getRecipe("noodles").displayRecipe(2);
【问题讨论】:
标签: javascript scope this settimeout