286 字
1 分钟
JavaScript - 惰性函数
定义:
一种优化模式,它在第一次调用后重新定义自己,后续调用直接返回第一次计算的结果,避免重复执行相同的逻辑。
实例:
在这里我们举出一个很常见的例子:复制文本
function copyText(text) { if (navigator.clipboard) { navigator.clipboard.writeText(text); } else { const input = document.createElement('input'); input.setAttribute('value', text); document.body.appendChild(input); input.select(); document.execCommand('copy'); document.body.removeChild(input); }}这是一个很常见的复制文本的函数,首先在进入函数时,判断浏览器是否支持Navigator Clipboard API,如果支持就执行此套API,如果不支持就执行传统复制方法
这只是一个很简单的例子,功能正常。但思考一下,有必要每次执行函数时都判断一次?
对于同一个浏览器,怎么可能一会支持新API,一会不支持API。
所以这个函数应该被确定下来,而不是每次都判断。
使用惰性函数:
function copyText(text) { if (navigator.clipboard) { copyText = (text) => { navigator.clipboard.writeText(text); }; } else { copyText = (text) => { const input = document.createElement('input'); input.setAttribute('value', text); document.body.appendChild(input); input.select(); document.execCommand('copy'); document.body.removeChild(input); }; }
copyText(text);}效果:
使用前:
使用后:

JavaScript - 惰性函数
https://blog.stoeaves.com/posts/js-lazy-function/ 评论加载中...