语法:
var funcion_name = new Function(argument1, argument2, ..., argumentN, function_body);
缺点:
尽管可用Function构造函数创建函数,但是最好还是不要使用它,因为它定义函数比用传统方式要慢的多。不过,所有函数都应该看作是Function类的实例。
扩展:
(1)因为函数是引用类型,所以它们也有属性和方法。属性length声明了函数期望的参数个数。例:
function doAdd(iNum){
alert(iNum +10);
}
function sayHi(){
Alert(“Hi”);
}
alert(doAdd.length); //输出“1”
alert(sayHi.length); //输出“0”
无论多少个参数,ECMAScript函数可以接受任意多个参数(最多25个)
(2)Function对象也有与所有对象共享的标准valueOf()方法和toString()方法,这两个方法返回的都是函数的源代码,在调试时尤其有用。
例:
function doAdd(iNum){
alert(iNum + 10);
}
alert(doAdd.toString());
//输出doAdd()函数的文本,即:
//function doAdd(iNum){ alert(iNum + 10); }
注意:
function,new function,new Function之间的区别:
var foo01 = function() //or fun01 = function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}
alert(typeof(foo01));
alert(foo01());
function
300 最普通的function使用方式,定一个JavaScript函数。两种写法表现出来的运行效果完全相同,唯一的却别是后一种写法有较高的初始化优先级。在大扩号内的变量作用域中,this指代foo01的所有者,即window对象。
使用方法二:
var foo02 = new function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}
alert(typeof(foo02));
alert(foo02.constructor());
300 这是一个比较puzzle的function的使用方式,好像是定一个函数。但是实际上这是定一个JavaScript中的用户自定义对象,不过这里是个匿名类。这个用法和函数本身的使用基本没有任何关系,在大扩号中会构建一个变量作用域,this指代这个作用域本身。
使用方法三:
var foo3 = new Function('var temp = 100; this.temp = 200; return temp + this.temp;');
alert(typeof(foo3));
alert(foo3());
300 使用系统内置函数对象来构建一个函数,这和方法一中的第一种方式在效果和初始化优先级上都完全相同,就是函数体以字符串形式给出。
使用方法四:
var foo4 = Function('var temp = 100; this.temp = 200; return temp + this.temp;');
alert(typeof(foo4));
alert(foo4());
function
300 这个方式是不常使用的,效果和方法三一样,不过不清楚不用new来生成有没有什么副作用,这也体现了JavaScript一个最大的特性:灵活!能省就省。