我有一位同事问我为什么他不能从回调函数访问事件参数。结果是 jquery 似乎在调用完成后将事件设置为 null 并创建一个临时局部变量解决了问题(见下文)。
然后我开始思考,为什么“消息”甚至可用于回调。有人可以解释一下吗?
$('some seletor').click({msg: message},function(event){
alert(event.data.msg); //event.data.msg is not available to the json callback because event is null
var message = event.data.msg; //message will be available to the callback...why?
$.getJSON('ajax/test.json', function(data) {
alert(message); //works ok - why is the message variable visible here at all, should it not have gone out of scope when the above function ended?
alert(event.data.msg); //will crash, seems that event has been set to null by the framework after the function finished
});
});
最佳答案
存在于给定范围内的任何变量可用于该范围内定义的所有函数。 (这就是在 JS 中定义作用域的方式,this part of the language specification 可能是一个很好的切入点,如果您想了解它的定义方式的话)。
由于定义回调函数的函数表达式在定义变量的函数内部,因此变量对它可用。
关于javascript - 为什么函数内的变量对该函数内声明的回调函数可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16997667/