Shane
Shane

Reputation: 5677

Function constructor in javascript

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

Upvotes: 1

Views: 85

Answers (2)

Ramzi Khahil
Ramzi Khahil

Reputation: 5052

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".

Upvotes: 1

Salem
Salem

Reputation: 1162

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"

Upvotes: 4

Related Questions