《JavaScript設計模式與開發》筆記 5.關於正確寫一個閉包

來源:互聯網
上載者:User

標籤:lock   驅動   define   block   設計   開發   cal   javascrip   var   

1.如何正確使用閉包
1.常用閉包
var asd =(function(){var value = 0    //私人變數放入記憶體return function(){   //biubiubiu 發射火箭}})();asd();

 

2.一個引用引發的閉包問題
var asdf = function(){    var value = 0;    return function(){        //火箭升空    }}var f = asdf(); //作為一個函數的引用引發閉包的問題

 

//這樣不是一個閉包

var asdf = function(){    var value = 0;    return function(){        //guang  爆炸了    }}//作為一個函數的引用asdf()();asdf()();asdf()();

 

3.對象
var asdf = {    a :0,    call:function(){        this.a++;        console.log(this.a);    }}asdf.call();   //輸出1asdf.call();   //輸出2asdf.call();   //輸出3

 

4.注意this指向問題

錯誤寫法:全都變成undefined

var asdf = {    a :0,    call:function(){        return function(){            this.a++;            console.log(this.a);        }    }}asdf.call()();   //輸出1asdf.call()();   //輸出2asdf.call()();   //輸出3正確寫法var asdf = {    a :0,    call:function(){        that = this;        return function(){            that.a++;            console.log(that.a);        }    }}asdf.call()();   //輸出1asdf.call()();   //輸出2asdf.call()();   //輸出3

 

5.基於事件驅動引發的閉包
for(var i=0;i<arguments.length;i++){    asdf.on某一個事件=function(){            //裡面也是一個閉包            }}

 

《JavaScript設計模式與開發》筆記 5.關於正確寫一個閉包

聯繫我們

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