[英]can callback functions access parent function variables
我有一個load(callback)函數,它將一個回調函數作為參數。 此回調函數可以訪問其父函數中存在的變量,即load()
(function load(callback)
{
return $.get("../somepage.aspx", {data:data}, function (response, status, xhr){
var x = 10;
if(typeof callback === 'function') { callback(); }
}
})(done);
var done = function(){
//do something with x here
alert(x);
}
您無法按自己的意願訪問x
因為x
超出了done
函數的范圍 。
您需要將x
傳遞給回調:
(function load(callback)
{
return $.get("../somepage.aspx", {data:data}, function (response, status, xhr){
var x = 10;
if(typeof callback === 'function') { callback(x); }
}
})(done);
var done = function(x){
//do something with x here
alert(x);
}
我懷疑這是您想要的,但是我在暗中摸索着看問題中的代碼有嚴重的語法問題(即done
不是父母的child
)。
不,不是因為回調的作用域完全在調用作用域之外。 在回調中傳遞x作為參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.