Javascript eval on global scope?
Is it possible to use the eval command to execute something with a global scope? For example, this will cause an error:
<script>
function execute(x){
eval(x);
}
function start(){
execute("var ary = new Array()");
execute("ary.push('test');"); // This will cause exception: ary is not defined
}
</script>
<html><body onLoad="start()"></body></html>
I know the 'with' keyword will set a specific scope, but is there a keyword for the global scope? Or is it possible to define a custom scope that would allow this to work?
<script>
var scope = {};
function execute(x){
with(scope){
eval(x);
}
}
function start(){
execute("var ary = new Array()");
execute("ary.push('test');"); // This will cause exception: ary is not defined
}
</script>
<html><body onLoad="start()"></body></html>
Essentially, what I am trying to do is have a global execute funciton...
(function(){
eval.apply(this, arguments);
}(a,b,c))
This will invoke eval using the global object, window
in browsers, as the this
argument passing any arguments you've passed into the anonymous function.
eval.call(window, x, y, z)
or eval.apply(window, arguments)
is also valid if you're certain window
is the global object. This isn't always true, however. For instance, the global object in a Node.js script is process
if I remember correctly.
Use (1, eval)('...')
.
$ node
> fooMaker = function () { (1, eval)('foo = "bar"'); };
[Function]
> typeof foo
'undefined'
> fooMaker()
undefined
> typeof foo
'string'
> foo
'bar'