No.46 question of BFE.dev, link here implement _.once().
function func(num) {
return num
}
const onced = once(func)
onced(1)
// 1, func called with 1
onced(2)
// 1, even 2 is passed, previous result is returned
we can see the code this question provides, first it pushed func into once, and once returned a funtion called onced, then it called onced and pushed 1 into it and get 1 as result, it called onced again and pushed 2, but still got the first time result.
So it’s actually a simple question, we can implement it easily, first we need to initialize a result which is equals to null and isCall which is equals to false. Then return a function, and take in spreaded args as parameters.
Then we check if isCall is true, if so, it means the function had been called, so just return result, if not, assign func.call(this, …args) to result, and change isCall’s status, finally return result.
function once(func) {
let result = null
let isCall = false
return function (...args) {
if (isCall) {
return result
}
result = func.call(this, ...args)
isCall = true
return result
}
}
And that’s all process to implement this function, hope it helpful.
本文解释了如何在JavaScript中实现一个名为`once`的函数,它确保一个函数仅被调用一次。通过使用闭包和状态管理,作者详细介绍了函数的工作原理和实现步骤,对初学者和开发者颇具指导意义。

被折叠的 条评论
为什么被折叠?



