implement `_.once()`【BFE.dev】

本文解释了如何在JavaScript中实现一个名为`once`的函数,它确保一个函数仅被调用一次。通过使用闭包和状态管理,作者详细介绍了函数的工作原理和实现步骤,对初学者和开发者颇具指导意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值