惰性函数理解

惰性载入表示函数执行的分支只会在函数第一次调用的时候执行,在第一次调用过程中,该函数会被覆盖为另一个按照合适方式执行的函数,这样任何对原函数的调用就不用再进行冗余的复杂执行了;

例如在事件绑定时:

function addEvent (type, element, fun) {
    if (element.addEventListener) {
        element.addEventListener(type, fun, false);
    }
    else if(element.attachEvent){
        element.attachEvent('on' + type, fun);
    }
    else{
        element['on' + type] = fun;
    }
}
上述每次调用时代码都会经过冗余的函数执行
function addEvent (type, element, fun) {
    if (element.addEventListener) {
        addEvent = function (type, element, fun) {
            element.addEventListener(type, fun, false);
        }
    }
    else if(element.attachEvent){
        addEvent = function (type, element, fun) {
            element.attachEvent('on' + type, fun);
        }
    }
    else{
        addEvent = function (type, element, fun) {
            element['on' + type] = fun;
        }
    }
    return addEvent(type, element, fun);
}
上述代码在第一次调用时,就会对addEvent方法进行重写,下次调用时直接调用重写后的方法,减少了冗余的调用
实例:创建AJAX时:

function createXHR() {
 4     var xhr;
 5     try{
 6         xhr = new XMLHttpRequest();
 7     }catch(e) {
 8         handleErr(e);
 9 
10         try {
11             xhr = new ActiveXObject("Msxml2.XMLHTTP");
12         }catch(e) {
13             try{
14                 xhr = new ActiveXObject("Microsoft.XMLHTTP");
15             }catch(e) {
16                 xhr = null;
17             }
18         }
19     }
20 
21     return xhr ;
22 }
23 
24 function handleErr(error) {
25     // 这一步在实战中很重要,因为catch会延长作用域链,所以是在全局作用域声明的e
26     // 这里我们把它赋给局部变量,则查找更快
27     var err = error;
28 
29     // do sth.
30 }
使用惰性函数重写后:

// 惰性函数
 2 // 第二次才生效
 3 // 作用:优化对于被频繁使用的函数
 4 function createXHR() {
 5     var xhr;
 6     if(typeof XMLHttpRequest != 'undefined') {
 7         xhr = new XMLHttpRequest();
 8         createXHR = function() {
 9             return new XMLHttpRequest();
10         }
11     }else {
12         try {
13             xhr = new ActiveXObject("Msxml2.XMLHTTP");
14             createXHR = function() {
15                 return new ActiveXObject("Msxml2.XMLHTTP");
16             }
17         }catch(e) {
18             try {
19                 xhr = new ActiveXObject("Microsoft.XMLHTTP");
20                 createXHR = function() {
21                     return new ActiveXObject("Microsoft.XMLHTTP");
22                 }
23             }catch(e) {
24                 createXHR = function () {
25                     return null;
26                 }
27             }
28         }
29     }
30     return xhr;
31 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值