javascript - 为什么函数内的变量对该函数内声明的回调函数可见?

标签 javascript jquery

我有一位同事问我为什么他不能从回调函数访问事件参数。结果是 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/

相关文章:

javascript - 第二列和第三列中的图像在悬停时随机消失

php - 为什么框架和此类弃用函数而不是仅仅更新它们?

javascript - Charts.js - 多系列折线图/条形图上堆积条形图的颜色不起作用

javascript - 修复网站中的特定链接仅适用于 iphone

jquery - D3 相当于 jQuery 属性选择器

javascript - Jquery - .toFixed(2) 固定数字减少到 3 位

javascript - Eclipse 的 JSDT 发生了什么?

javascript - 无法将 nodemailer 错误响应从 node.js 发送到 angular.js

javascript - 创建时访问对象内容

javascript - $(document).ready 仅在 IE 中触发一次,但在 Firefox 中有效