首页 > 代码库 > JavaScript Patterns 4.7 Init-Time Branching
JavaScript Patterns 4.7 Init-Time Branching
When you know that a certain condition will not change throughout the life of the program, it makes sense to test the condition only once. Browser sniffing (or feature detection) is a typical example.
// BEFOREvar utils = { addListener : function(el, type, fn) { if ( typeof window.addEventListener === ‘function‘) { el.addEventListener(type, fn, false); } else if ( typeof document.attachEvent === ‘function‘) {// IE el.attachEvent(‘on‘ + type, fn); } else {// older browsers el[‘on‘ + type] = fn; } }, removeListener : function(el, type, fn) { // pretty much the same... }};// AFTER// the interfacevar utils = { addListener : null, removeListener : null};// the implementationif ( typeof window.addEventListener === ‘function‘) { utils.addListener = function(el, type, fn) { el.addEventListener(type, fn, false); }; utils.removeListener = function(el, type, fn) { el.removeEventListener(type, fn, false); };} else if ( typeof document.attachEvent === ‘function‘) {// IE utils.addListener = function(el, type, fn) { el.attachEvent(‘on‘ + type, fn); }; utils.removeListener = function(el, type, fn) { el.detachEvent(‘on‘ + type, fn); };} else {// older browsers utils.addListener = function(el, type, fn) { el[‘on‘ + type] = fn; }; utils.removeListener = function(el, type, fn) { el[‘on‘ + type] = null; };}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。