3

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.

1
  • 3
    Why are you using new Function at all in this case? There is a big yellow note in the MDN documentation, it can hardly be overlooked: "Note: Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. [...]" Commented Feb 18, 2015 at 19:26

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

So you need to make that variables global.

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

Comments

0

You need to pass the variable as a parameter to the created function.

(function(){
    const myVar = 1000;
    (new Function("return alert(n);"))(myVar);
})();

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.