![](/img/trans.png)
[英]Do variables declared inside callback functions remain in memory or are they destroyed upon end of callback execution?
[英]Why are variables inside functions visible to callback functions declared inside that function?
我有一位同事問我為什么無法從回調函數中訪問事件參數。 事實證明,在調用完成后,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中工作,如果你想要了解它的定義,那么這部分語言規范可能是一個很好的切入點)。
由於定義回調的函數表達式位於定義變量的函數內部,因此該變量可用。
試試這個:
$('some seletor').click({msg: message},function(ev){
alert(ev.data.msg);
var message = ev.data.msg;
$.getJSON('ajax/test.json', function(data) {
alert(message);
alert(ev.data.msg);
});
});
而不是event
。 因為事件是全局對象window.event
,所以當事件結束時它變為未定義。 您可以使用事件對象而不從以下參數中獲取它:
$('some seletor').click({msg: message},function(){
alert(event.data.msg);
});
如果您原諒偽代碼 - 嘗試將其視為嵌套塊 - 這種事情
function foo()
{
int bar=0;
//inner block
{
bar++;
}
}
或者更具體地說
function click()
{
variable {msg: message}
//inner block
function(ev)
{
....
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.