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);
}

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

9 Comments

@fuyushimoya Thanks. Updated.
This does not answer the question. He is asking about accessing parent variables
@leo.fcx Admittedly 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.)
@Petrichor, agree. Actually, IMO that explanation should go in the answer :)
@Petriocher thnks a lot that helps!!
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.