在下面的代码:Javascript:为什么具有全局执行上下文的回调函数可以访问范围变量?
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被作用域进行测试,这是回调函数被定义在哪里。因为logCb()函数不能访问x变量,所以我会预计行cb()
会抛出一个错误。
但事实并非如此。为什么?看起来回调函数中的引用是在赋值过程中创建的,而不是在执行过程中创建的 - 如果您考虑提升 - 即在编译过程中,回调函数被提升到“test”的顶部,然后赋值在测试中发生范围?
我已经读过,执行与作用域不一样。在本文中: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
似乎暗示回调是从测试函数中调用的。
因为在我看来,不管在哪里调用回调函数,它仍然会被测试范围。
我想我的问题是:
如何在回调函数中定义的条款来处理,然后考虑范围和执行上下文时调用?
你有没有听说过在JavaScript关闭? –
函数的作用域是基于它声明的地方,而不是从那里调用的地方。函数的'this'与范围无关,并且基于* how *函数被调用。 – nnnnnn
@RajaprabhuAravindasamy。所以回调已经结束了测试? –