Function的应用

来源:互联网 发布:结构设计软件体系 编辑:程序博客网 时间:2024/05/22 11:30

Function()构造器创建的函数与函数直接量声明、匿名函数不同,它在任意位置创建的实例,都处于创建的全局闭包中;原因,在于Function()构造器传入的参数全部是字符串,因此不必要与函数局部变量建立引用。由此带来的一个好处是:在任意多层的函数内部,都可以通过Function()创建函数而不至于导致闭包不能释放。

例一、function myFun(){var value = "this is local";var foo = function(){console.log(value);}foo(); //this is local(function(){console.log(value);})()    //this is localfunction f1(){console.log(value);}f1();    //this is localvar f2 = new Function('console.log(value)');f2();  //this is global}myFun();

例二、var obj = new Object();var events = {m1:"clicked",m2:"changed",m3:"mousemove"};for(e in events){obj[e] = function(){    console.log(events[e]);        }}for(i in obj){obj[i]();}//结果://mousemove//mousemove//mousemove

例三、var obj = new Object();var events = {m1:"clicked",m2:"changed",m3:"mousemove"};for(e in events){obj[e] = new Function("console.log(events['"+e+"'])");}for(i in obj){obj[i]();}//结果://clicked//changed//mousemove

解决例二的途径还有以下方式:

var obj = new Object();var events = {m1:"clicked",m2:"changed",m3:"mousemove"};for(e in events){obj[e] = function(aValue){return function(){console.log(events[aValue]);}}(e)}或者for(e in events){    function(){        var aValue = e;        obj[e]=function(){            console.log(events[aValue]);        }    }();}或者for(e in events){    (obj[e] = function(){        console.log(events[arguments.callee.aValue]);    }    ).aValue=e;}for(i in obj){    obj[i]();}
//结果://clicked//changed//mousemove




原创粉丝点击