I’d like to execute a function from the top of the stack. That is, any variables defined with “var” should be defined in the global sense. Is this possible? fn.call(window) doesn’t work.
<script>
var foo = "I am top level foo.";
var fn = function(){
var foo = "Setting foo from in a function";
}
fn.call(window); //doesn't work, var is still set locally in fn.
alert(foo); //desired effect will alert "setting foo from in a function"
</script>
Please note: I am fully aware that not specifying “var” makes an item a global variable. The problem is that I can not specify the contents of “fn”, it is user-defined, but expected to be run from the top level.
I’m willing to use eval if necessary.
I’m not sure what you’re trying to do, but you cannot overwrite the value of
foothat way. When you specifiedvar fooin the global context, it is attached to the global object (in global scope).When you then specified
var foowithin your function, you declared it within the scope of that function. This means that it is unknown to the outside world+. What you could do, is something like this:Or to be more explicit:
Is this what you want?
+ When you defined
fooinside the function, it was attached to the Activation object and not the Global object. Every time you enter the execution context for a function, a new Activation object is created. So every time you call the function, you’re getting a newfoo. This is just as well, otherwise you wouldn’t be able to create variables that are local in scope to the function; they would leak into the global context.UPDATE
I guess you could do something like the following if you really want to evaluate code inside a function in a global context. It’s ugly, and I’m not sure why you’d want to do it, but here goes:
This will strip out
(function () {and})so that you end up with only the code in the middle, which you then run througheval.Once again, I have to stress that I don’t recommend doing this.