函數是javascrpit中的一等公民,提供了function關鍵字和Function()這個內置對象。
function和new function()以及new Function()之間的區別一直都會讓人形成困擾,下面是一些簡單的學習心得。java
最經常使用的function用法就是定義函數函數
var foo = function(){ var temp = 100; this.temp = 200; return temp + this.temp ; }; alert(typeof foo); alert(foo()); //或者 function foo(){ var temp = 100; this.temp = 200; retrun temp + this.temp; } // 輸出結果都是 function 和300 // 惟一的區別在於後者是函數聲明,他的初始化優先級比前者(表達式)要高,不管放在任何位置,都會在同一做用域中第一個表達式被解析前解析。
其實這並非一個函數,而是聲明一個用戶自定義對象,是一個匿名對象。學習
var foo = new function(){ var temp = 100; this.temp = 200; return temp + this.temp; }; alert(typeof foo); alert(foo.temp) alert(foo.constructor()); // 輸出結果是 Objcect 200 300 // 由於foo並非函數,所以不能之間執行
Function是一個系統內置的函數對象。
使用該方法來聲明一個函數。this
var foo = new Function('var temp = 100; this.temp = 200; return temp + this.temp;'); alert(typeof foo); alert(foo()); //在括號中,最後一個逗號前都是該函數的參數,最後一個逗號後面的內容是函數體 //另外這裏加不加new 關鍵字,好像對結果沒有任何影響 //ps:這樣定義函數的好處和用途目前尚未搞懂,惟一的用途是能夠在頁面的文本框中定義函數,直接執行。