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); };