0

i have a load(callback) function which takes a callback function as parameter. Can this callback function access variables present in its parent function i.e. 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);
}
user3399326
  • 863
  • 4
  • 13
  • 24

2 Answers2

1

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 (i.e. done is not a child of parent.)

Alex Booker
  • 10,487
  • 1
  • 24
  • 34
0

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