JavaScript常用設計模式

來源:互聯網
上載者:User

標籤:單例   函數傳回值   nbsp   原廠模式   建立對象   javascrip   eth   執行函數   模組   

單例模式:確保類只能被執行個體化一次。

var obj = {}2、函數傳回值var func = function () {return {}}var obj = func();3、建構函式初始化var obj = (function () {return {}})()

 

裝飾者模式:裝飾者用用於封裝同介面的對象。

var obj = obj || {}obj.set = function(){}obj.get = function(){}obj.……= function(){}

 

模組模式:該模式使用閉包封裝私人狀態和組織。

var module = (function(obj){})({});

 

觀察者模式:它定義了一種一對多的關係,讓多個觀察者對象同時監聽某一個主題對象。

function func() {}func.prototype.set = function(opt){}func.prototype.get = function(opt){}var obj = new func();obj.set({});obj.get({});

 

建構函式模式:自訂自己的建構函式,然後在裡面聲明自訂類型對象的屬性或方法。 

1、建構函式function func(name,age){this.id = 0;//code……}func.prototype.pro = function(){}2、建構函式強制執行個體化function func(title) {    if (!(this instanceof func)) {        return new func(title);    }    this.title = title;}func.prototype.get = function () { return this.title; }console.log(obj.get());

 

原廠模式:原廠模式就好比現實生活中的工廠可以產生大量相似的產品。

function func(opt){var obj = {id:0,title:‘‘}return $.extend(obj,opt);}var f1 = func({id:1,title:‘標題1‘});var f2 = func({id:2,title:‘標題2‘});

 

對象建立模式:對象中建立對象

模式1:命名空間(namespace)var obj = obj || {};obj.app = obj.app || {};obj.app.ios = obj.app.ios || {};obj.app.android = obj.app.android || {};模式2:通過自執行函數建立對象var obj;(function () {obj = {}})模式3:鏈模式var obj = {func1: function () {return this;},func2: function () {return this;},……: function () {return this;}}// 鏈方法調用obj.func1().func2().……();模式4:函數文法糖函數文法糖是為一個對象快速添加方法(函數)的擴充,這個主要是利用prototype的特性if (typeof Function.prototype.method !== "function") {    Function.prototype.method = function (name, implementation) {        this.prototype[name] = implementation;        return this;    };}var func = function (name) {    this.name = name;}.method(‘set‘, function (name) {    this.name = name;           }).method(‘get‘, function () {    return this.name;});var a = new func(‘a‘);a.set(‘b‘);console.log(a.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.