JavaScript 單例,Hash,拋異常

來源:互聯網
上載者:User

標籤:this   script   org   javascrip   規範   prototype   asc   http   reference   

1. 單例 ECMA 5 版

記得以前寫過幾種單例實現,找不到了。。。

1 function Singleton() {2     if (this.constructor.instance) {3         return this.constructor.instance;4     }5     this.constructor.instance = this;6 7     this.val = ...  8 }

利用了 Object.prototype.constructor 來存放單例instance

 

2. Hash 

反正一般都是用object來當hashmap用,但是key的類型一定是字串,畢竟JSON規範。用了數字或其他類型作key也會被轉成string

 

3. 拋異常

throw "Exception blahblah";

throw 後面接什麼類型都行?這破JS也太自由了。

 

JavaScript 單例,Hash,拋異常

聯繫我們

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