欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解new function(){}和function(){}() 區(qū)別分析

 更新時間:2008年03月22日 14:00:10   作者:  
只要 new 表達式之后的 constructor 返回(return)一個引用對象(數(shù)組,對象,函數(shù)等),都將覆蓋new創(chuàng)建的匿名對象,如果返回(return)一個原始類型(無 return 時其實為 return 原始類型 undefined),那么就返回 new 創(chuàng)建的匿名對象。
情景一:
var yx01 = new function() {return "圓心"};
alert(yx01);
我們運行情景一代碼,將返回顯示“[object object] ”,此時該代碼等價于:

function 匿名類(){
    return "圓心";
}
var yx01 = new 匿名類();
alert(yx01);我們對情景一的代碼進行下面改造:

var yx01 = new function() {return new String("圓心")};
alert(yx01);
我們運行,將會發(fā)現(xiàn)返回的是“圓心”,這是為什么呢?

只要 new 表達式之后的 constructor 返回(return)一個引用對象(數(shù)組,對象,函數(shù)等),都將覆蓋new創(chuàng)建的匿名對象,如果返回(return)一個原始類型(無 return 時其實為 return 原始類型 undefined),那么就返回 new 創(chuàng)建的匿名對象
由于 new String 會構造一個對象,而不是一個 string 直接量,且new String(x) 如果帶參數(shù),那么alert它的時候就會返回 x。所以 yx01 將返回 new String(”圓心”) 這個對象,而 alert yx01 則顯示 “圓心”。

情景二:

var yx02 = function() {return "圓心"}();
alert(yx02);我們運行情景二代碼,將返回顯示“圓心”,此時該代碼等價于:

var 匿名函數(shù) = function() {return "圓心"};
yx02 = 匿名函數(shù)();
alert(yx02);很明顯,yx02 返回的是匿名函數(shù)的執(zhí)行結果值,即 yx02 為:“圓心”。

當然匿名函數(shù)的執(zhí)行結果也可以為一個匿名對象。具體常見應用可以看《Javascript的一種模塊模式

相關文章

最新評論