跳到主要内容

惰性函数

举例:如复制功能,有navigator.clipboard则直接使用它,没有的时候,使用JS实现。

但有没有navigator.clipboard的判断,没必要每次都执行,判断一次就够了

lazy-function.js
function createCopyText(){
if(navigator.clipboard){
return (text) => {
navigator.clipboard.writeText(text);
}
} else {
return (text) => {
// 使用JS实现复制功能
const input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
}
}

// 可以随时调用createCopyText()来完成初始化
// const copyText = createCopyText();
// 之后直接调用copyText()来完成复制功能
// copyText('要复制的文本');