Restricting eval() to a narrow scope

前端 未结 8 2173
误落风尘
误落风尘 2020-11-27 04:51

I have a javascript file that reads another file which may contain javascript fragments that need to be eval()-ed. The script fragments are supposed to conform to a strict s

8条回答
  •  被撕碎了的回忆
    2020-11-27 05:19

    Don't execute code you don't trust. Globals will always be accessible. If you do trust the code, you can execute it with particular variables in it's scope as follows:

    (new Function("a", "b", "alert(a + b);"))(1, 2);
    

    this is equivalent to:

    (function (a, b) {
        alert(a + b);
    })(1, 2);
    

提交回复
热议问题