new Function scope

五迷三道 提交于 2020-03-26 07:59:14

问题


I've got a piece of code with a ReferenceError here

or below:

function foo() {

    function bar() {
        console.log('bar');
    }

    var x = new Function('bar();');
    x();
}

foo(); // ReferenceError: bar is not defined

Is it possible to make this happen? I mean the bar function to exist inside the new Function


回答1:


Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called.

— MDN

So no, it isn't while using that approach.

Don't use the function constructor. It is inefficient, and converting strings to code is fraught with problems.

function foo() {

    function bar() {
        alert('bar');
    }

    function x() {
      bar();
    }
    x();
}

foo();



回答2:


One possible approach is to use eval instead of new Function:

function foo() {

    function bar() {
        console.log('bar');
    }

    eval('x = function() { bar(); }');
    x();
}

foo(); // works fine.


来源:https://stackoverflow.com/questions/31762457/new-function-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!