您的位置:首页 > 其它

Function构造函数

2016-07-09 00:35 225 查看
  使用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: