Function构造函数

  使用Function构造函数, 也能够创建函数, 和使用关键字function定义函数有几点区别:

  使用function关键字这样定义函数:

var f = function(x,y) {return x+y};

  使用Function构造函数定义函数要这样写:

var f = new Function("x", "y", "return x+y");

  使用new Function构造函数创建函数有3个注意点:

  1:在JS运行的时候可以动态创建Function;

  JQ作者写的模板引擎就是通过new Function形式创建出来的:http://ejohn.org/blog/javascript-micro-templating/

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
  
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
      
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
        
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
        
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
    
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

  2:Function()构造函数创建的函数的执行效率比较低;

        var a = new Date();
        var x = a.getTime();
        for(var i=0;i<100000;i++){
            function EE(){   //使用function语句定义的空函数
                
            }
        }
        var b = new Date();
        var y = b.getTime();
        alert(y-x);    //62,不同环境和浏览器会存在差异
        // 测试Function构造函数定义的空函数执行效率
        var a = new Date();
        var x = a.getTime();
        for(var i=0;i<100000;i++){
            new Function();  //使用Function构造函数定义的空函数
        }
        var b = new Date();
        var y = b.getTime();
        alert(y-x);    //2390

  3:Function()构造函数创建的函数执行作用域是全局的;

        var fn = new Function("x", "return x*x+y");
        var y = 3;
        alert(fn(3));
        (function(){
            var y = 2;
            alert(fn(3));
        }());

 

作者: NONO
出处:http://www.cnblogs.com/diligenceday/
QQ:287101329
微信:18101055830 

转载于:https://www.cnblogs.com/diligenceday/p/5529182.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值