1. 程式人生 > >JavaScript常用設計模式

JavaScript常用設計模式

OS names his 方法 end nta imp androi 關系

單例模式:確保類只能被實例化一次。

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常用設計模式