Javascript eval on global scope?

后端 未结 6 829
长发绾君心
长发绾君心 2020-12-01 10:33

Is it possible to use the eval command to execute something with a global scope? For example, this will cause an error:



        
相关标签:
6条回答
  • 2020-12-01 10:43

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

    Further Reading.

    0 讨论(0)
  • 2020-12-01 10:48

    I know there will be lot of comments coming in with eval is evil and I agree with that. However, to answer your question, change your start method as follows:

    function start(){   
      execute("ary = new Array()");   
      execute("ary.push('test');");  // This will cause exception: ary is not defined  
    } 
    
    0 讨论(0)
  • 2020-12-01 10:49

    To execute some JavaScript in the global scope you can call it indirectly by using setTimeout() or if you are using jQuery, take a look at $.globalEval().

    Changing your execute method to the following will allow you to still use the 'var' keyword:

    function execute(x) {
        setTimeout("eval(" + x + ")", 0);
        // Or: $.globalEval(x);
    }
    
    
    function start() {
        try
        {
            execute("var ary = new Array()");
            execute("ary.push('test');");
        }
        catch (e)
        {
            alert(e);
        }
    }
    
    
    start();
    
    0 讨论(0)
  • 2020-12-01 10:55
    (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.

    0 讨论(0)
  • 2020-12-01 10:55

    Use eval.apply(null, ["code"]);.

    eval.apply(this, ["code"]); does not work on Microsoft Script Host (cscript.exe).

    0 讨论(0)
  • 2020-12-01 11:01

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

    $ node
    > fooMaker = function () { (1, eval)('foo = "bar"'); };
    [Function]
    > typeof foo
    'undefined'
    > fooMaker()
    undefined
    > typeof foo
    'string'
    > foo
    'bar'
    
    0 讨论(0)
提交回复
热议问题