javascript new Function('')和new function(){}執行個體

來源:互聯網
上載者:User

情景一:

 代碼如下 複製代碼
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);

我們運行,將會發現返回的是“圓心”,這是為什麼呢?
只要 new 運算式之後的 constructor 返回(return)一個引用對象(數組,對象,函數等),都將覆蓋new建立的匿名對象,如果返回(return)一個原始類型(無 return 時其實為 return 原始類型 undefined),那麼就返回 new 建立的匿名對象。(謝謝 Lunatic_Sun ,描述更精準點)
由於 new String 會構造一個對象,而不是一個 string 直接量,且new String(x) 如果帶參數,那麼alert它的時候就會返回 x。所以 yx01 將返回 new String(“圓心”) 這個對象,而 alert yx01 則顯示 “圓心”。
情景二:

 代碼如下 複製代碼
var yx02 = function() {return "圓心"}();
alert(yx02);

我們運行情景二代碼,將返回顯示“圓心”,此時該代碼等價於:

 代碼如下 複製代碼
var 匿名函數 = function() {return "圓心"};
yx02 = 匿名函數();
alert(yx02);

很明顯,yx02 返回的是匿名函數的執行結果值,即 yx02 為:“圓


執行個體

 代碼如下 複製代碼

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <script>
        var f = new Function('x', 'y', 'return x + y;');// 等價於var f = function(x, y){return x + y;}
        console.log(f(1, 1));
        var str = '{"id": 108}';
        console.log((new Function('return ' + str))());// 字串轉對象

        f = new function() {return 'ca';};
        console.log(f);
        // 相當於
        /*function 匿名類() {
            return 'ca';
        }
        f = new 匿名類();
        console.log(f);*/
        f = new function() {return new String('ca');};
        console.log(f);
        // 只要 new 運算式之後的 constructor 返回(return)一個引用對象(數組,對象,函數等),都將覆蓋new建立的匿名對象,如果返回(return)一個原始類型(無 return 時其實為 return 原始類型 undefined),那麼就返回 new 建立的匿名對象
    </script>
</body>
</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.