js实现 after

实现 after 方法
在 JavaScript 中实现 after 方法可以用于在某个函数被调用指定次数后再执行另一个函数。以下是几种实现方式:
使用闭包和计数器
function after(times, func) {
let count = 0;
return function(...args) {
count++;
if (count >= times) {
return func.apply(this, args);
}
};
}
// 示例用法
const sayHello = after(3, () => {
console.log('Hello!');
});
sayHello(); // 无输出
sayHello(); // 无输出
sayHello(); // 输出: Hello!
使用 ES6 类和装饰器模式
class After {
constructor(times, func) {
this.times = times;
this.func = func;
this.count = 0;
}
execute(...args) {
this.count++;
if (this.count >= this.times) {
return this.func.apply(this, args);
}
}
}
// 示例用法
const sayHi = new After(2, () => {
console.log('Hi!');
});
sayHi.execute(); // 无输出
sayHi.execute(); // 输出: Hi!
使用 Promise 实现异步版本
function afterAsync(times, func) {
let count = 0;
return function(...args) {
return new Promise((resolve) => {
count++;
if (count >= times) {
resolve(func.apply(this, args));
}
});
};
}
// 示例用法
const greet = afterAsync(2, () => {
return 'Greetings!';
});
greet().then(console.log); // 无输出
greet().then(console.log); // 输出: Greetings!
实现 lodash 风格的 after
如果需要与 lodash 的 _.after 方法保持兼容,可以这样实现:
function lodashAfter(times, func) {
if (typeof func !== 'function') {
throw new TypeError('Expected a function');
}
times = Math.max(times, 0);
return function(...args) {
if (--times < 1) {
return func.apply(this, args);
}
};
}
// 示例用法
const logDone = lodashAfter(3, () => {
console.log('Done!');
});
logDone(); // 无输出
logDone(); // 无输出
logDone(); // 输出: Done!
这些实现方式可以根据具体需求选择使用,闭包版本是最简洁的通用实现。







