Variable not in scope

I think I’m misunderstanding the basics of variable scoping / closures.

function myFunc(){
setTimeout(function(myVar){return myFunc;}('value'), 1);

How can I make the variable myVar available to myFunc (only changing the setTimeout line)?

Ideally you would change myFunc to have a parameter named myVar, but since your requirement is to change only the setTimeout line, then I think your only option is to use a global variable.

A better way of putting the question might be:

Is it possible to change the execution scope of a previously defined function?

The answer to that question is to use one of the following:


Those will let you change the “this” binding, but not the scope.

I don’t think that it is possible to change the execution scope.

I may not be able to answer the for rest of the day, but for what purpose are you intending to achieve?

As Jeff points out, those change the context, not the scope.

The reason for this question came from dealing with passing parameters to a previously defined function that was being used as an AJAX callback (or called from an AJAX callback, I can’t remember now). I’ll see if I can come up with an example, but it might be a day or two because I’m working on different stuff today.

Well I had a look at trying to create an example, and I don’t think there is any real practical use to it. It’s more a theoretical question than a practical one.

My original problem that led me to asking this question was AJAXifying some code - some of the functions being called were relying on certain variables being in scope, which then weren’t in scope when called from an AJAX callback. If it was possible to change the execution scope, this problem could be avoided.

The simple solution, as Jeff points out, is to just modify those functions so that they take the variables as arguments.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.