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

本文探讨了JavaScript中使用函数构造器创建函数的方法,并解释了其如何动态生成和编译代码的过程。文章通过实例展示了函数构造器的特性,尤其是它在作用域上的独特行为。

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;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值