在以下代码中:
function test() {
var x = 5 // scoped to test function
console.log(this); // global object
logCb(function(){
console.log(this); // global object
console.log(x);
})
}
function logCb (cb) {
console.log(this); // global object
cb() // This still seems to execute within the test function scope? why...
}
test()
x 的作用域是测试,这是定义回调函数的地方。我本来希望行cb()
会引发错误,因为 logCb() 函数无权访问 x 变量。
然而,这种情况并非如此。为什么?似乎回调中的引用是在分配期间创建的,而不是在执行期间创建的——如果你考虑提升,我想这是有道理的——即在编译期间,回调函数是否被提升到“测试”的顶部,然后分配发生在测试中范围?
我读过执行与范围不同。在这篇文章中:http ://ryanmorr.com/understanding-scope-and-context-in-javascript/ ,这句话scope pertains to the variable access of a function when it is invoked and is unique to each invocation
似乎暗示回调是从测试函数内部调用的。
因为在我看来,无论在哪里调用回调函数,它仍然会被限定在测试范围内。
我想我的问题是:
在考虑范围和执行上下文时,如何在定义和调用方面处理回调函数?