Laser said:
What are the differences between these two methods of executing code
which is in a string?
In particular code the main difference cannot be observed, because you
have defined `d' in global execution context. Here the difference is
in the Scope Chain of execution contexts created by eval code and by
execution of the function object created by Function constructor.
Execution context for eval code uses caller's Variable Object for its
VO during variable instantiation. Functions created by Function
constructor never form closure. The internal [[Scope]] property always
refers Global Object and Global Object is used for VO in global
execution context. This is the reason that you cannot observe the main
difference.
<script type='text/javascript'>
var d="I'm d";
var h="alert(d);";
//method 1
eval(h);
The Scope Chain for eval execution context contains:
Global Object
//method 2
(new Function(h))();
The Scope Chain here is:
GlobalObject
^
VariableObject of execution context for function code
If you would like to see the difference try out:
(function () {
var d="I'm d";
var h="alert(d);";
eval(h); //OK
(new Function(h))(); //ReferenceError
})();