http://qiutc.me/post/this-this-this-in-javascript.htmljavascript
1 // js經常使用設計模式的實現思路,單例,工廠,代理,裝飾,觀察者模式等 2 3 // 1) 單例: 任意對象都是單例,無須特別處理 4 5 var obj = {name: 'michaelqin', age: 30}; 6 7 // 2) 工廠: 就是一樣形式參數返回不一樣的實例 8 function Person() { this.name = 'Person1'; } 9 function Animal() { this.name = 'Animal1'; } 10 11 function Factory() {} 12 Factory.prototype.getInstance = function(className) { 13 return eval('new ' + className + '()'); 14 } 15 16 var factory = new Factory(); 17 var obj1 = factory.getInstance('Person'); 18 var obj2 = factory.getInstance('Animal'); 19 console.log(obj1.name); // Person1 20 console.log(obj2.name); // Animal1 21 22 //3) 代理: 就是新建個類調用老類的接口,包一下 23 function Person() { } 24 Person.prototype.sayName = function() { console.log('michaelqin'); } 25 Person.prototype.sayAge = function() { console.log(30); } 26 27 function PersonProxy() { 28 this.person = new Person(); 29 var that = this; 30 this.callMethod = function(functionName) { 31 console.log('before proxy:', functionName); 32 that.person[functionName](); // 代理 33 console.log('after proxy:', functionName); 34 } 35 } 36 37 var pp = new PersonProxy(); 38 pp.callMethod('sayName'); // 代理調用Person的方法sayName() 39 pp.callMethod('sayAge'); // 代理調用Person的方法sayAge() 40 41 //4) 觀察者: 就是事件模式,好比按鈕的onclick這樣的應用. 42 function Publisher() { 43 this.listeners = []; 44 } 45 Publisher.prototype = { 46 'addListener': function(listener) { 47 this.listeners.push(listener); 48 }, 49 50 'removeListener': function(listener) { 51 delete this.listeners[listener]; 52 }, 53 54 'notify': function(obj) { 55 for(var i = 0; i < this.listeners.length; i++) { 56 var listener = this.listeners[i]; 57 if (typeof listener !== 'undefined') { 58 listener.process(obj); 59 } 60 } 61 } 62 }; // 發佈者 63 64 function Subscriber() { 65 66 } 67 Subscriber.prototype = { 68 'process': function(obj) { 69 console.log(obj); 70 } 71 }; // 訂閱者 72 73 var publisher = new Publisher(); 74 publisher.addListener(new Subscriber()); 75 publisher.addListener(new Subscriber()); 76 publisher.notify({name: 'michaelqin', ageo: 30}); // 發佈一個對象到全部訂閱者 77 publisher.notify('2 subscribers will both perform process'); // 發佈一個字符串到全部訂閱者