惰性函数(懒函数)
优点
:避免多次重复的步骤判断,第一次调用判定后,不用重复进行判断。
应用
:常用于函数库的编写,单例模式之中。在固定的应用环境不会发生改变,频繁要使用同一判断逻辑的。
如浏览器兼容判断
js
function getCss(element, attr){
if('getComputedStyle' in window){
getCss = function(element, attr){
return window.getComputedStyle(element)[attr];
}
}else{
getCss = function(element, attr){
return element.currentStyle[attr];
}
}
return getCss(element, attr);
}
getCss(document.body, 'margin'); // 第一次调用会进行判断,后面的调用使用第一次的判断结果,不会再次判断。
getCss(document.body, 'padding');
getCss(document.body, 'width');
function getCss(element, attr){
if('getComputedStyle' in window){
getCss = function(element, attr){
return window.getComputedStyle(element)[attr];
}
}else{
getCss = function(element, attr){
return element.currentStyle[attr];
}
}
return getCss(element, attr);
}
getCss(document.body, 'margin'); // 第一次调用会进行判断,后面的调用使用第一次的判断结果,不会再次判断。
getCss(document.body, 'padding');
getCss(document.body, 'width');