_.before(n, func)

96

_.before(n, func)
_.before创建一个会调用func的函数,会绑定this,限制func调用的次数,超过限制次数之后调用这个被创建的函数会返回最后一次func结果

参数

n (number): 限制func只能被调用几次
func (Function):被限制的方法

返回值

(Function): 返回新的被限制的方法

例子

 

jQuery(element).on('click', _.before(5, addContactToList));
// => Allows adding up to 4 contacts to the list.

 

源代码:

/**
 * 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.
 *
 * @since 3.0.0
 * @category Function
 * @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
 *
 * jQuery(element).on('click', before(5, addContactToList))
 * // => Allows adding up to 4 contacts to the list.
 */
//创建一个会调用func的函数,会绑定this,限制func调用的次数,超过限制次数之后调用这个被创建的函数会返回最后一次func结果
function before(n, func) {
  let result//闭包内的结果变量
  if (typeof func != 'function') {//如果func不是function,抛出错误
    throw new TypeError('Expected a function')
  }
  return function(...args) {//创建一个限制func调用次数的方法
    if (--n > 0) {//当限制次数n自减后还大于0,就apply调用func存下结果
      result = func.apply(this, args)
    }
    if (n <= 1) {//当n小于等于1,将func赋值为undefined
      func = undefined
    }
    return result//返回闭包变量result
  }
}

export default before

 

posted @ 2018-11-13 09:59  hahazexia  阅读(275)  评论(0)    收藏  举报