function, new function, new Function

關鍵字: javascript

函數是JavaScript中很重要的一個語言元素,並且提供了一個function關鍵字和內置對象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());  



運行結果:
object
300 
這是一個比較puzzle的function的使用方式,好像是定一個函數。但是實際上這是定一個JavaScript中的用戶自定義對象,不過這裏是個匿名類。這個用法和函數本身的使用基本沒有任何關係,在大擴號中會構建一個變量作用域,this指代這個作用域本身。


使用方法三: 

var foo3 = new Function('var temp = 100; this.temp = 200; return temp + this.temp;');
alert(typeof(foo3));
alert(foo3());
 
運行結果: 
function
300 
使用系統內置函數對象來構建一個函數,這和方法一中的第一種方式在效果和初始化優先級上都完全相同,就是函數體以字符串形式給出。


使用方法四:

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

alert(typeof(foo4));
alert(foo4());


運行結果:

function
300
  
這個方式是不常使用的,效果和方法三一樣,不過不清楚不用new來生成有沒有什麼副作用,這也體現了JavaScript一個最大的特性:靈活!能省就省。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章