JavaScript單例模式

來源:互聯網
上載者:User

標籤:

一、什麼是單例

  意思是指擷取的對象只有一份。

二、最通用的單例 

任何時刻擷取SingLeton.instance都是同一個對象

1  var SingLeton={2        instance:{3             property:1,4             getProperty:function(){return this.property;}5         }  6 }

三、轉變成通過函數的方法來擷取對象

類似於SingLeton()(),但是問題來了,每次執行都會重新建立instance對象,如果已經存在那麼無需再建立

var Singleton=function(){    var instance={        property:1,        getProperty:function(){return this.property;}    };    var getInstance=function(){        return instance;    }    return getInstance;}console.log(Singleton()());
var Singleton=function(){    var instance=null;
function createInstance(){ return { property:1, getProperty:function(){return this.property;} }; } var getInstance=function(){ instance=instance||createInstance(); return instance; } return getInstance;}console.log(Singleton()());

問題又來了,怎麼不像其他語言那樣,通過SingLeton.getInstance()來擷取對象呢

四、自調用函數

要想改造成SingLeton.getInstance(),那SingLeton必須一出來就是一個對象,該對象包含一個方法,可以返回instance對象,我們想到採用讓函數立即執行的方式


 
var Singleton=(function(){    var instance=null;    function createInstance(){
console.log("create");
return { property:1, getProperty:function(){return this.property;} }; } return { getInstance:function(){ instance=instance||createInstance(); return instance; } }})()console.log(Singleton.getInstance());
console.log(Singleton.getInstance());

//result:
create 
Object {property: 1}getProperty: (){return this.property;}

 
Object {property: 1}getProperty: (){return this.property;}
 

 

至此單例出來了,可以驗證下

 

 

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.