1

HTML:

<textarea id="ta" cols="20" rows="20">alert("Hello World");</textarea>
<input type="button" value=" Exec " onclick="exec()" />

JS:

function exec()
{
    var code=document.getElementById('ta').value;
    var fn=new Function(code);
    fn();
}

http://jsfiddle.net/3Z5qP/6/

Can anyone tell me the logic behind the code on how it display's "Hello World" and i was looking at the MDN

Does this code above creates a new alert function for me using the new Function constructor

2 Answers 2

4

Function(string) returns a function with string as its body. That code grabs the text in the text area, inserts it into the body of a function, and then runs it. In this case, the code is the single command, alert("Hello World");.

You can try it in a simpler example:

var t = new Function('alert("hello, world")');
t(); // Alerts "hello, world"
Sign up to request clarification or add additional context in comments.

4 Comments

If i am not wrong, it creates a function t() with the code alert("Hello World"), well basically is there anyway i can look what is inside the function t()
Well, the contents of the function are exactly the string you passed it. In your example, the contents of the text box are the contents of the function.
Not sure if it helps, but if you, for some reason, don't get to see the way the function was constructed, you can always call something like t.toString() to see its body.
Thanks. This should help a lot.
1

Well, first of all you need to know that JavaScript is an interpreted language. This means that the code is evaluated and executed on the fly.

Another thing to know is that everything in JavaScript is an object, even functions. So what is happening is that you take the text with document.getElementById('ta').value then use it to build a new function, which is called fn. Then it gets executed.

If you want real in-depth stuff look for something like "javascript execution environment".

Comments

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.