js 魔法小书
this理解
- 一个函数被直接调用的时候,属于全局调用,这时候它的 this 指向 全局对象。严格模式 ‘use strict’下undefined。
- 当一个函数被当作一个对象的方法调用的时候,this 指向函数所在的这个对象; setTimeout坑可使用闭包。
- 当作构造函数调用时,this 指向了这个构造函数调用时候实例化出来的对象。
- 箭头函数中的 this 只和定义它时候的作用域的 this 有关,而与在哪里以及如何调用它无关,同时它的 this 指向是不可改变的。
- call, apply, bind 可指定 this。
http://qiutc.me/post/this-this-this-in-javascript.html
js常用设计模式的实现思路
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'); // 发布一个字符串到所有订阅者