Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 529
wuntee Avatar asked Jan 12 '11 15:01

wuntee


3 Answers

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

like image 78
orca Avatar answered Nov 20 '22 13:11

orca


Use (1, eval)('...').

$ node
> fooMaker = function () { (1, eval)('foo = "bar"'); };
[Function]
> typeof foo
'undefined'
> fooMaker()
undefined
> typeof foo
'string'
> foo
'bar'
like image 38
pyrospade Avatar answered Nov 20 '22 13:11

pyrospade


You should be able to use eval() in global scope by calling it indirectly. However, not all browsers are currently doing this.

Further Reading.

like image 6
alex Avatar answered Nov 20 '22 13:11

alex