javascript 中function(){},new function(),new Function(),Function 简单介绍

Posted 笠航

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 中function(){},new function(),new Function(),Function 简单介绍相关的知识,希望对你有一定的参考价值。

函数是javascript中很重要的一个语言元素,并且提供了一个function关键字和内置对象Function,下面是其可能的用法和它们之间的关系。

function使用方式

 var foo01 = function() //或 function foo01()
 {  
     var temp = 100;  
     this.temp = 200;  
     return temp + this.temp;  
 }  
 alert(typeof(foo01));  // function 
 alert(foo01());          // 300 

最普通的function使用方式,定一个JavaScript函数。两种写法表现出来的运行效果完全相同,唯一的却别是后一种写法有较高的初始化优先级。在大扩号内的变量作用域中,this指代foo01的所有者,即window对象。

new function()使用方式

var foo02 = new function()  
 {  
     var temp = 100;  
     this.temp = 200;  
     return temp + this.temp;  
 }  

 alert(typeof(foo02));    //object 
 alert(foo02.constructor());   //300   

这是一个比较puzzle的function的使用方式,好像是定一个函数。但是实际上这是定一个JavaScript中的用户自定义对象,不过这里是个匿名类。这个用法和函数本身的使用基本没有任何关系,在大扩号中会构建一个变量作用域,this指代这个作用域本身。(理解为实例化匿名类)

new Function()使用方式

var foo3 = new Function(‘var temp = 100; this.temp = 200; return temp + this.temp;‘);  

 alert(typeof(foo3));  //object
 alert(foo3());           //300

使用系统内置函数对象来构建一个函数,这和方法一中的第一种方式在效果和初始化优先级上都完全相同,就是函数体以字符串形式给出。

Function()使用方式

var foo4 = Function(‘var temp = 100; this.temp = 200; return temp + this.temp;‘);  

 alert(typeof(foo4));     //function
 alert(foo4());              //300

这个方式是不常使用的,效果和方法三一样,不过不清楚不用new来生成有没有什么副作用,这也体现了JavaScript一个最大的特性:灵活!能省就省。(不推荐使用)

以上是关于javascript 中function(){},new function(),new Function(),Function 简单介绍的主要内容,如果未能解决你的问题,请参考以下文章

javascript 中函数 function啥作用

在javascript中Function和function有啥区别?

javascript 中function(){},new function(),new Function(),Function 简单介绍

javascript中Function与Object

浅析JavaScript中Function对象

JavaScript Function 函数深入总结