_.once(func)

107

_.once(func)

_.once创建一个函数被限制只能调用func函数一次。重复调用这个函数就会返回第一次调用时的结果。

参数

func (Function): 被限制的函数

返回值

(Function): 返回被限制的函数

例子

var initialize = _.once(createApplication);
initialize();
initialize();
// => `createApplication` is invoked once

源代码:

import before from './before.js'

/**
 * Creates a function that is restricted to invoking `func` once. Repeat calls
 * to the function return the value of the first invocation. The `func` is
 * invoked with the `this` binding and arguments of the created function.
 *
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new restricted function.
 * @example
 *
 * const initialize = once(createApplication)
 * initialize()
 * initialize()
 * // => `createApplication` is invoked once
 */
//创建一个函数被限制只能调用func函数一次。重复调用这个函数就会返回第一次调用时的结果。
function once(func) {
  return before(2, func)
}

export default once
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.
 *
 * @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-29 16:40  hahazexia  阅读(225)  评论(0)    收藏  举报