Reputation: 5677
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();
}
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
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
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