Web开发中,因为浏览器之间的差异实现差异,一些嗅探工作总是不可避免的,比如我们需要在各个浏览器中能够通用事件绑定函数addEvent
//一般写法 //缺点:当他每次被调用的时候都都会执行里面的if条件, var addEvent = function(elem, type, handler){ if(window.addEventLister){ return elem.addEventListener(type, handler, false); } if(window.attachEvent){ return elem.attachEvent('on'+type, handler); } } //改进 var addEvent = (function(){ if(window.addEventListener){ return function(elem, type, handler){ elem.addEventListener(type, handler, false); } } if(window.attachEvent){ return function(elem, type, handler){ elem.atttachEvent('on'+handler); } } })(); //惰性载入方案 var addEvent = function(elem, type, handler){ if(window.addEventListener){ addEvent = function(elem, type, handler){ elem.addEventListener(type, handler, false); } } else if(window.atttachEvent){ addEvent = function(elem, type, handler){ elem.atttachEvent('on'+type, handler); } } addEvent(elem, type, handler); };