创建一个调用函数,使调用次数不操过n次,之后再调用这个函数,将返回一次最后调用func的结果

/**
 * 创建一个调用函数,通过this绑定和创建函数的参数调用func,调用次数不操过n次,之后再调用这个函数,
 * 将返回一次最后调用func的结果
 * Creates a function that invokes `func`, with the `this` binding and arguments
 * of the created function, while it's called less than `n` times. Subsequent calls
 * to the created function return the result of the last `func` invocation
 *
 * @param {number} n The number of calls at which `func` is no longer invoked
 * @param {Function} func The function to restrict
 * @returns {Function} Returns the new restricted function
 * @example
 * document.getElementById("btn").addEventListener("click", before(5, this.add))
 * // this.add函数最多执行4次
 */

import toInteger from "./toInteger" // 我的博客搜索【转换为整数】
const FUNC_ERROR_TEXT = "Expected a function"

function before(n, func) {
  var result
  if (typeof func !== "function") {
    throw new TypeError(FUNC_ERROR_TEXT)
  }
  n = toInteger(n)
  return function() {
    if (--n > 0) {
      result = func.apply(this, arguments)
    }
    if (n <= 1) {
      func = undefined
    }
    return result
  }
}

export default before
//参考例子

import React, { Component } from "react"
import before from "./before"

class Demo extends Component {
  state = {
    num: 0
  }

  componentDidMount() {
    document
      .getElementById("btn")
      .addEventListener("click", before(5, this.add))
  }

  add = () => {
    this.setState(prev => ({
      num: prev.num + 1
    }))
  }

  render() {
    return (
      <>
        <p className="code">
          创建一个调用函数,通过this绑定和创建函数的参数调用func,调用次数不操过n次,之后再调用这个函数,将返回一次最后调用func的结果
        </p>
        <p className="code">
          <button type="button" id="btn">
            点击我+1
          </button>
        </p>
        <p className="comment">{this.state.num}</p>
      </>
    )
  }
}

export default Demo

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值