每日一个lodash方法之after

/*

* The opposite of `before`. This method creates a function that invokes

* `func` once it's called `n` or more times.

* 跟before函数相反,该方法会在调用n次之后触发一次func

*

* @since 0.1.0

* @category Function

* @param {number} n The number of calls before `func` is invoked. func触发之前该方法调用的次数

* @param {Function} func The function to restrict. 被限制的函数

* @returns {Function} Returns the new restricted function.

* @example

*

* const saves = ['profile', 'settings']

* const done = after(saves.length, () => console.log('done saving!'))

*

* forEach(saves, type => asyncSave({ 'type': type, 'complete': done }))

* // => Logs 'done saving!' after the two async saves have completed.

*/

function after(n, func) {

if (typeof func != 'function') {

throw new TypeError('Expected a function')

}

return function(...args) {

if (--n < 1) { // 闭包,使用的n变量一直是传进aftern

return func.apply(this, args)

}

}

}

你可能感兴趣的:(前端)