首页 > 网站 > WEB开发 > 正文

JavaScript Patterns 4.7 Init-Time Branching

2024-04-27 14:22:37
字体:
来源:转载
供稿:网友

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)


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表