[Javascript] Lazy Overriding
Let's see the following code
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);
}
}
Any problem with this code?
So why everytime we call copyText
function, we have to do navigator.clipboard
feature detection again?
Feature detection won't change anyhow, in theory, we only need to do the feature detection once;
Of course, in this example, it won't cause any performance overload with feature detection, it's just an example, but there will be some cases, doing check everytime is time consuming when function get called .
The way to can resolve this issue is by using Function Lazy overriding:
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);
}
So for the first time exeuction:
After the first time:
分类:
Javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-11-23 [Javascript] Sanitizing User Input in Javascript
2022-11-23 [XState + Typescript] Type XState
2022-11-23 [XState + React] using @xstate/inspect to display state machine char in webapp
2020-11-23 [Tools] API Extractor Setup for Typescript
2015-11-23 [Protractor] Testing With Protractor Page Objects
2015-11-23 [Protractor] Test Simple Binding With Protractor
2015-11-23 [Angular 2] A Simple Form in Angular 2