文章出處

  使用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 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()