js实现after

实现 after 方法
在 JavaScript 中实现 after 方法,可以在指定函数执行一定次数后再触发回调。以下是两种常见的实现方式:

基于计数器的方式
function after(times, callback) {
let count = 0;
return function() {
count++;
if (count >= times) {
return callback.apply(this, arguments);
}
};
}
// 使用示例
const done = after(3, function() {
console.log('执行完成');
});
done(); // 无输出
done(); // 无输出
done(); // 输出"执行完成"
使用闭包和剩余参数
function after(n, fn) {
return function(...args) {
if (--n < 1) {
return fn.apply(this, args);
}
};
}
// 使用示例
const save = after(2, function(name) {
console.log(`保存完成: ${name}`);
});
save('文件1'); // 无输出
save('文件2'); // 输出"保存完成: 文件2"
实现 DOM 的 after 方法
如果需要实现类似 jQuery 的 after 方法,用于在 DOM 元素后插入内容:
Element.prototype.after = function(...nodes) {
const parent = this.parentNode;
if (parent) {
let nextSibling = this.nextSibling;
nodes.forEach(node => {
parent.insertBefore(
node instanceof Node ? node : document.createTextNode(String(node)),
nextSibling
);
});
}
return this;
};
// 使用示例
const div = document.createElement('div');
div.textContent = '原始元素';
document.body.appendChild(div);
div.after('插入的文本', document.createElement('span'));
注意事项
- 函数式
after适用于需要延迟执行回调的场景 - DOM
after方法需考虑浏览器兼容性,现代浏览器已原生支持此方法 - 使用原型扩展时需注意不要覆盖已有方法






