Javascript的函数是运行时定义的,可以随时替换函数定义,非常的灵活。
我们先加入一个函数,用于判断是否是chrome
function isChrome() {
return /chrome/i.test(navigator.userAgent);
}
经常会有类似这样的需求,根据浏览器环境,执行不同的功能,常规做法是这样
function normalCreate() {
if (isChrome()) {
console.log('normal create in chrome');
} else {
console.log('normal create in other browser');
}
}
normalCreate();
normalCreate();
normalCreate();
chrome控制台的输出
normal create in chrome
normal create in chrome
normal create in chrome
这很常见,就不做讲解了。
我们假设isChrome是一个非常消耗性能的函数,每次都执行一次isChrome,电脑和用户都会十分痛苦。这时就可以用惰性函数定义(Lazy Function Definition)来解决这个问题,在《Javascript高级程序设计》中,翻译为惰性载入函数,怎么看都是一个惰加载图片的意思……咱们还是叫惰性函数定义吧.
可以像这样改写:
function lazyLoadCreate () {
console.log('first creating'); // pos-1
if (isChrome()) {
lazyLoadCreate = function () {
console.log('create function in chrome');
}
} else {
lazyLoadCreate = function () {
console.log('create function in other browser');
}
}
return lazyLoadCreate();
}
lazyLoadCreate();
lazyLoadCreate();
lazyLoadCreate();
chrome 控制台的输出
first creating
create function in chrome
create function in chrome
create function in chrome
还有另一种写法,更加简洁
var lazyLoadCreate = (function() {
console.log('first creating');
if (isChrome()) {
return function () {
console.log('create function in chrome');
}
} else {
return function () {
console.log('create function in other browser');
}
}
})();
可见lazyloadCreate在第一次执行这个函数时被替换了, pos-1处只执行了一次
我公司有个支付小网站,就需要根据进入时是微信还是支付宝进入,决定不同的支付方式与界面主题,这时就可以用到惰性函数定义(Lazy Function Definition)
网友评论