1、简洁的队列初始化:查询对象中某个属性,存在直接返回值,不存在,初始化该属性;
一般写法:
var obj = {}; var getQueue = (key) => { if (!obj[key]) { obj[key] = [] } return obj[key] }
精简写法:
export default function mitt(all: EventHandlerMap) { all = all || Object.create(null); return { /** * Register an event handler for the given type. * * @param {String} type Type of event to listen for, or `"*"` for all events * @param {Function} handler Function to call in response to given event * @memberOf mitt */ on(type: string, handler: EventHandler) { (all[type] || (all[type] = [])).push(handler); } }; }
2、无符号右移>>>:在搜索的事件监听函数不存在时,会返回一个极大的正数,传入 splice 后,并不会删除已有的函数监听器,从而实现了想要的功能。
亮眼代码:
/** * Remove an event handler for the given type. * * @param {String} type Type of event to unregister `handler` from, or `"*"` * @param {Function} handler Handler function to remove * @memberOf mitt */ off(type: string, handler: EventHandler) { if (all[type]) { all[type].splice(all[type].indexOf(handler) >>> 0, 1); } }标签:简洁,obj,代码,param,event,handler,key,type,优秀 From: https://www.cnblogs.com/vicky-li/p/18418004