我有一个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);
}发布于 2015-08-03 18:11:02
您不能按需要访问x,因为它位于done函数的https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript之外。
您需要将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 )。
发布于 2015-08-03 18:13:29
不,它不能这样做,因为回调的作用域完全超出了调用范围。将x作为回调中的参数传递。
https://stackoverflow.com/questions/31793940
复制相似问题