问题
is there any way to make the code below working?
(function(){
var n = "abc";
(new Function("return alert(n);"))();
})();
If I run the code in browser result is: "Uncaught ReferenceError: n is not defined".
Also, I need to some other variables like "n" make accessible inside the "new Function" too.
Please help, Thank you
回答1:
So you need to make that variables global.
(function(){
window.n = "abc";
(new Function("return alert(n);"))();
})();
回答2:
When you use the new Function
method (which is similar to eval
by the way), your code is executed in the global scope! n
only exists inside that anonymous function, it's not global.
You shouldn't be using new Function
unless it's 100% necessary.
(function(){
var n = "abc";
(function(){return alert(n);})();
})();
P.S. alert
returns undefined
so return alert()
doesn't do anything useful.
来源:https://stackoverflow.com/questions/28592127/javascript-new-function-scope-referenceerror