【JS】惰性函数

现有一段代码,根据浏览器兼容情况选择复制文本的方式

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)
  }
}

由于初次调用时就可以确定使用哪种方式,无需每次都判断。使用惰性函数优化代码

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)
}

但是上面代码会有副作用(更改了外部的函数),也可以使用高阶函数,由于自调用,所以会影响首次加载速度。

const copyText = (function (text) {
  if (navigator.clipboard) {
    return (text) => { navigator.clipboard.writeText(text) }
  } else {
    return (text) => {
      const input = document.createElement('input')
      input.setAttribute('value', text)
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
    }
  }
})()

如果比较在意纯函数则建议高阶函数的写法,这种写法没有副作用,但是会影响首屏加载速度,如果只有当函数第一次调用时才确定,那么第一种写法更优。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田本初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值