[英]can callback functions access parent function variables
i have a load(callback) function which takes a callback function as parameter. 我有一个load(callback)函数,它将一个回调函数作为参数。 Can this callback function access variables present in its parent function ie load() 此回调函数可以访问其父函数中存在的变量,即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);
}
You cannot access x
like you want because it is outside the scope of the done
function. 您无法按自己的意愿访问x
因为x
超出了done
函数的范围 。
You need to pass x
to the callback: 您需要将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);
}
I suspect this is what you want but to but I am taking a stab in the dark here seeing as how the code in the question has serious syntax problems (ie done
is not a child
of parent.) 我怀疑这是您想要的,但是我在暗中摸索着看问题中的代码有严重的语法问题(即done
不是父母的child
)。
Nope, it can't because the callback's scope is totally outside the calling scope. 不,不是因为回调的作用域完全在调用作用域之外。 Pass x as a parameter in the callback. 在回调中传递x作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.