js設計模式小結

來源:互聯網
上載者:User

標籤:綜合   小結   需要   模式   this   判斷   blog   執行個體   xiaomi   

1 建構函式模式

var Person = function(name){this.name = name;this.getName = function(){console.log(this.name);}};var Person1= new Person(‘xiaoming‘);Person1.getName();var Person2 = new Person(‘xiaohua‘);Person2.getName();

使用建構函式模式可以實現重複建立多個相似對象,且可以實現自訂傳參,但缺點是每次執行個體化一個對象時就相當於將該對象方法重新建立了一遍。

 2 原型模式

var Person = function(){};Person.prototype.name = ‘xiaoming‘;Person.prototype.getName = function() {console.log(this.name);};var Person1 = new Person();Person1.getName();var Person2 = new Person();Person2.getName();

原型模式的優點在於,每次執行個體化一個對象時,不需要重新建立該對象方法,而是通過指標引用原型鏈的方法,缺點是不能自訂傳參,所以就有了下面的建構函式和原型組合使用的模式
 3 建構函式+原型模式

var Person = function(name){this.name = name;};Person.prototype.getName = function() {console.log(this.name);};var Person1 = new Person(‘xiaoming‘);Person1.getName();var Person2 = new Person(‘xiaohua‘);Person2.getName();

綜合了建構函式和原型模式的雙方優點
4 原廠模式

function createPerson(name){var Person = new Object();Person.name = name;Person.getName = function(){console.log(this.name);} return Person;}var Person1= createPerson(‘xiaoming‘);Person1.getName();var Person2= createPerson(‘xiaohua‘);Person2.getName();

原廠模式也可以用於建立多個相似對象,與建構函式函數模式相似,主要區別是在內部通過new Object()建立對象最後return 出來,但是存在無法判斷物件類型的問題

5 模組模式

var person = function(name){function getName(name){console.log(name);}return {getName: getName}}();person.getName(‘xiaoming‘);

特別是在單頁應用中常用的模式,可以理解為引入了私人變數特權方法的單例。

js設計模式小結

相關文章

聯繫我們

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