js常见的设计模式,持续更新...

216 阅读1分钟

手写发布订阅

class EventEmitter {
	constructor(){
		this.events = {}
	}
	//订阅事件的方法
	on(eventName,callback){
		if(this.events[eventName]){
			this.events[eventName].push(callback)
		}else{
			this.events[eventName] = [callback]
		}
	}
	//触发事件的方法
	emit(eventName){
		this.events[eventName] && this.events[eventName].forEach(cb => cb())
	}
	//移除订阅事件
	removeListener(eventName,callback){
		if(this.events[eventName]){
			this.events[eventName] = this.events[eventName].filter(cb => cb !== callback)
		}
	}
	//只执行一次订阅的事件,然后移除
	once(eventName,callback){
		let fn = () => {
			callback()
			this.removeListener(eventName,fn)
		}
		this.on(eventName,fn)
	}
}

手写单例模式

//instance做判断
//用闭包保证instance不丢失(闭包延长变量的存活周期)
//立即执行函数
const Login = (function(){
	function Login(state){
    	this.state = state
    }
    Login.prototype.show(){
    	console.log(state)
    }
    
    let instance = null
    return function Single(...args){
    	if(!instance){
        	instance = new Login(...args)
        }
        return instance
    }
})()

//
const Login = (function(){
	class Login {
    	constructor(state){
        	this.state = state
        }
        
        show(){
    		console.log(state)
    	}
    }
	
    let instance = null
    return function Single(...args){
    	if(!instance){
        	instance = new Login(...args)
        }
        return instance
    }
})()

类形式的化,可以参考:

const Login = (function(){
	class Login{
		constructor(state){
			this.state = state
		}

		show(){
			console.log(this.state)
		}
	}

	let instance = null
	return function Sington(...args){
		if(!instance){
			instance = new Login(...args)
		}
		return instance
	}

})()

blog.csdn.net/weixin_4396…