JavaScript Patterns 4.7 Init-Time Branching

王朝学院·作者佚名  2016-05-23
窄屏简体版  字體: 小  |  中  |  大  |  超大  

javaScript Patterns 4.7 Init-Time Branching 2014-06-15 23:41 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑 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; };}

References:

Javascript Patterns -by Stoyan Stefanov(O`Reilly)

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航