javascript---a very important point of function constructor(Function())

4056 단어 Constructor
as we know,we can create a function with function constructor.like this:

  
var f = new F unction ( " x " , " y " , return " x*y; " );

it is equivalent to a function defined with normal syntax:

  
function f(x,y)
{
return x*y;
}

the function constructor expects any number of string arguments separated from each other by semicolons,the last augument is treated as the body of function;
Notes that there is not a argument is treated as the name of the function,so the function constructor creates anonymous functions.
we can see the above function created by function constructor,the function body is "x*y;",it is surprised,the body is just a string statement,so how does it do??let me explain the reason,the function contructor allows the javascript code to be dynamically created and compiled at runtime,it does something that is the same as eval () function does;
a very important point of function constructor
code comes first:

  
var name = " global " ;

  
function Fun()
  {
   
var name = " local " ;
   
return new Function( " return name " );
  }
  alert(Fun()());//the result

who can tell me what the result is??
it's amazed,it displays global.why??beacuse when we create a function with function constructor,the function is always compiled as if it is top level function,the function constructor does not use the local scope;

좋은 웹페이지 즐겨찾기