javascriptfunctionscopereferenceerror

JavaScript new Function scope ReferenceError


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.


Solution

  • So you need to make that variables global.

    (function(){
        window.n = "abc";
        (new Function("return alert(n);"))();
    })();