惰性载入表示函数执行的分支只会在函数第一次调用的时候执行,在第一次调用过程中,该函数会被覆盖为另一个按照合适方式执行的函数,这样任何对原函数的调用就不用再进行冗余的复杂执行了;
例如在事件绑定时:
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; } }
上述每次调用时代码都会经过冗余的函数执行
实例:创建AJAX时: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方法进行重写,下次调用时直接调用重写后的方法,减少了冗余的调用
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 }