JS中超越現實的匿名函數__javascript

來源:互聯網
上載者:User

一般函數:

function show1(name){        alert(name); //列印:zhangsan    }show1("zhangsan");

匿名函數:

var show2 = function (name) {        alert(name); //列印:張三    }show2("張三");

上面2種定義函數的區別:
1.我們知道所有的function都會在window對象裡

    function show1(name){        alert(name); //列印:張三    }    window.show1("張三");

即使在函數定義之前調用

    window.show1("張三");    function show1(name){        alert(name); //列印:張三    }

這是因為這種”有名字”的函數在JS引擎初始化的時候就載入到範圍裡面

2.如果是匿名函數

    window.show2("李四");    var show2 = function (name) {        alert(name); //列印:李四    }

控制台會列印:TypeError: window.show2 is not a function

二、如果我們需要合并上面2個函數

<script>   function show(name) {       return function () {           alert(name); //內建函式是可以調用外層的變數的       }   }   show("王五");</script>

猜猜會列印什麼。什麼也沒有,也不會報錯。這是因為執行show()只是返回了一個函數本身,並沒有執行這個函數。

show("王五")();

這樣執行,就列印:王五

如果裡面的函數也要傳入變數

<script>   function show(name) {       return function (age) {           alert(name); //列印:王五           alert(age);  //列印:18       }   }   show("王五")(18);</script>
<script>   function show(name) {       return function (name) {           alert(name);       }   }   show("王五")(18);</script>

猜猜是列印“王五”還是“18”。只會列印“18”。

三、匿名函數的自執行

<script>    (function (name) {        alert(name);    //列印:哈哈    })("哈哈")</script>

以上是推薦的寫法。
其他寫法:

    -function (name) {        alert(name);    //列印:哈哈    }("哈哈")
    +function (name) {        alert(name);    //列印:哈哈    }("哈哈")
    !function (name) {        alert(name);    //列印:哈哈    }("哈哈")
    [function (name) {        alert(name);    //列印:哈哈    }("哈哈")]
    new function (name) {        alert(name);    //列印:哈哈    }("哈哈")
    ~function (name) {        alert(name);    //列印:哈哈    }("哈哈")
    void function (name) {        alert(name);    //列印:哈哈    }("哈哈")

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.