惰性函数

127 阅读1分钟

思考一下下面的代码:

    // 复制粘贴
    function copyText(text) {
      if (navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1) {
        window.clipboardData.setData('Text', text);
      } else {
        let input = document.createElement('input');
        input.value = text;
        document.body.appendChild(input);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
      }
    }

上面的copyText的功能是复制文本到剪切板, 并对低版本的IE做了兼容处理, 每次运行的copyText函数都会进行一次ua的判断,而userAgent总是固定的,通常不会变化,因此可以直接使用惰性函数来进行优化:

    // 惰性函数
    let copyTextLazy = (text)=> {
      if (navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1) {
        copyTextLazy = () => window.clipboardData.setData('Text', text);
      } else {
        copyTextLazy = () => {
        let input = document.createElement('input');
        input.value = text;
        document.body.appendChild(input);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
        }
      }
      copyTextLazy();
    }

惰性函数的特点是当程序出现分支时,在执行一次之后该函数的实现就固定了,不再需要进行判断。适用于代码逻辑有多个分支,且分支条件不会发生变化的场景。