lodash源码阅读(三)——before()

# before()

_.before(n, func)

此方法创建一个函数,通过this绑定调用fun,其调用次数不超过n次。之后再调用这个函数将返回最后一次调用fun的返回值。(与after()相反,可先了解after()

before()源码
/**
 * 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.
 * 创建一个调用func的函数,当这个函数调用次数不超过 n 次时,通过this绑定和创建函数的参数调用func。 之后再调用这个函数,将返回一次最后调用func的结果。
 *
 * @since 3.0.0
 * @category Function 函数类
 * @param {number} n The number of calls at which `func` is no longer invoked.
 * n:number  超过n次'func'不再调用
 * @param {Function} func The function to restrict.
 * func:function  限制函数
 * @returns {Function} Returns the new restricted function.
 * 返回:函数  新的限制函数
 *
 * @example
 *
 * jQuery(element).on('click', before(5, addContactToList))
 * // => Allows adding up to 4 contacts to the list.
 * // => 允许向列表添加四个联系人
 */
function before(n, func) {
  let result
  if (typeof func !== 'function') {
    throw new TypeError('Expected a function')
  }
  return function(...args) {
    if (--n > 0) {
      result = func.apply(this, args)
    }
    if (n <= 1) {
      func = undefined
    }
    return result
  }
}

export default before

posted @ 2022-10-15 16:19  苟苟苟  阅读(30)  评论(0)    收藏  举报