JavaScript Patterns 4.7 Init-Time Branching
2014-06-15 23:41 小郝(Kaibo Hao) 阅读(324) 评论(0) 编辑 收藏 举报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.
// BEFORE var 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 interface var utils = { addListener : null, removeListener : null }; // the implementation if ( 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)
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。