javascript設計模式-單例模式

來源:互聯網
上載者:User

標籤:通過   span   變數   命名空間   特權   etag   name   func   log   

單例模式,是建立型設計模式的一種,又被稱為單體模式,是只允許執行個體化一次的對象類。有時也用來規劃一個命名空間。

 1 var Util = { 2     getName: function () { 3         console.log(‘wp‘) 4     }, 5     getAge: function () { 6         console.log(25) 7     }, 8     getAll: function () { 9         this.getName();10         this.getAge();11     }12 }13 Wang.getAll()

除了可以用來定義命名空間外,還可以管理程式碼程式庫的各個模組。

例:

 1 var Util = { 2     Tool: { 3         tool1: function () { 4             ... 5         }, 6         too2: function () { 7             ... 8         } 9     },10     Ajax: {11         get: function () {12             ...13         },14         post: function () {15             ...16         }17     },18     Animate: {19         move: function () {20             ...21         },22         rotate: function () {23             ...24         }25     }26 }27 Util.Tool.tool1();

例外,使用單例模式,還可以設定無法修改的靜態變數

var Conf = (function () {    var conf = {        CONF_A: 100,        CONF_B: 200,        CONF_C: 300    }    return {        get: function (name) {            return conf[name] ? conf[name] : null        }    }})();var conf_a = Conf.get(‘CONF_A‘);console.log(conf_a);  // 100

說明:因為將靜態變數定義在函數對象裡,而函數內部只提供了get方法,因此只能在外部通過特權方法訪問到這些靜態變數,但是無法修改這些靜態變數

 

javascript設計模式-單例模式

聯繫我們

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