惰性载入表示函数执行的分支只会在函数第一次掉用的时候执行,在第一次调用过程中,该函数会被覆盖为另一个按照合适方式执行的函数,这样任何对原函数的调用就不用再经过执行的分支了。
1、事件监听
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);
}
2、原生Ajax
function createXHR(){
var xhr=null;
if(typeof XMLHttpRequest!='undefined'){
xhr=new XMLHttpRequest();
createXHR=function(){
return XMLHttpRequest(); //直接返回一个懒函数,这样不必在往下走
}
}else{
try{
xhr=new ActiveXObject("Msxml2.XMLHTTP");
createXHR=function(){
return new ActiveXObject("Msxml2.XMLHTTP");
}
}catche(e){
try{
xhr =new ActiveXObject("Microsoft.XMLHTTP");
createXHR=function(){
return new ActiveXObject("Microsoft.XMLHTTP");
}
}catch(e){
createXHR=function(){
return null
}
}
}
}
}
可以总结出在哪些情况下使用惰性函数:
1 应用频繁,如果只用一次,是体现不出它的优点出来的,用的次数越多,越能体现这种模式的优势所在;
2 固定不变,一次判定,在固定的应用环境中不会发生改变;