问题
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