简体   繁体   中英

can callback functions access parent function variables

i have a load(callback) function which takes a callback function as parameter. Can this callback function access variables present in its parent function ie 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.

You need to pass x to the callback:

(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.)

Nope, it can't because the callback's scope is totally outside the calling scope. Pass x as a parameter in the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM