现有一段代码,根据浏览器兼容情况选择复制文本的方式
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)
}
}
})()
如果比较在意纯函数则建议高阶函数的写法,这种写法没有副作用,但是会影响首屏加载速度,如果只有当函数第一次调用时才确定,那么第一种写法更优。