或許許多人對此不以爲然,在函數前加 new 關鍵字,不就是實例化一個對象嗎?但事情顯然沒那麼簡單:
function Test() {
this.name ='Test';
return function() {return true; }
}
var fnT = Test(); //返回function() { return true; }
var newT=new Test(); // 返回function() { return true; }
newT是一個 Test 對象嗎?錯!這裏 newT是一個函數——Test 中返回的 function() { return true; }。這時,new Test() 等效於 Test(),注意,是等效於,不是等於,如果使用new Test() == Test() 判定兩者是否相等,則會返回 false,因爲 Javascript 對於 Object 和 Function 的比較是基於引用的。
爲了更清晰的分辨在上述情形下兩者間的區別,請繼續看以下代碼:
function Test() {
this.name ='Test';
return 'aaaa';
}
var fnT = Test(); //返回 ‘aaaa‘
var newT = new Test(); //返回Test{ name="Test"}
顯然,fnT 是字符串 aaaa,那 newT 呢?呵呵,是不是被第一個樣例迷惑了?其實,此時 newT 是一個 Test 對象——有一個名爲 name 的屬性,其值爲字符串 Test。
總結:
如果函數返回值爲常規意義上的值類型(Number、String、Boolean)時,new 函數將會返回一個該函數的實例對象,而如果函數返回一個引用類型(Object、Array、Function),則 new 函數與直接調用函數產生的結果等同。
參考:http://blog.csdn.net/orain/article/details/7104984