惰性载入函数处理的方式有两种:
- 在函数被调用时再处理函数。
function createXRH(){
if(typeof XMLHttpRequest != 'undefined'){
console.log('XMLHttpRequest');
createXHR = function(){
console.log(1);
return new XMLHttpRequest();
}
}else if(typeof ActiveXObject != 'undefined'){
console.log('ActiveXObject');
createXHR = function(){
console.log(2);
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
return createXHR();
}
var xhr = createXRH();
console.log('xhr',xhr);
var xhr1 = createXRH();
console.log('xhr1',xhr1);
- 在声明函数时就指定适当的函数。
var createXHR = (function(){
if(XMLHttpRequest){
return function(){
return new XMLHttpRequest();
}
}else if(ActiveXObject){
return function(){
return new ActiveXObject();
}
}
})()
console.log(createXHR);
惰性载入函数的优点是:
只在执行分支代码时牺牲一点儿性能。上面这两种方式都能避免执行不必要的代码。