js实现tap
实现 tap 方法
在 JavaScript 中,tap 是一种函数式编程工具,允许在链式调用中插入调试或副作用操作而不中断链式流程。以下是几种实现方式:
使用函数封装
const tap = (value, fn) => {
fn(value);
return value;
};
// 使用示例
const result = tap([1, 2, 3], console.log).map(x => x * 2);
// 输出: [1, 2, 3]
// result 为 [2, 4, 6]
原型链扩展(不推荐污染原型)
Object.defineProperty(Object.prototype, 'tap', {
value: function(fn) {
fn(this);
return this;
},
enumerable: false
});
// 使用示例
[1, 2, 3].tap(console.log).map(x => x * 2);
使用 Proxy 实现
const createTappable = (target) => new Proxy(target, {
get(target, prop) {
if (prop === 'tap') {
return fn => {
fn(target);
return createTappable(target);
};
}
return createTappable(target[prop]);
}
});
// 使用示例
const arr = createTappable([1, 2, 3]);
arr.tap(console.log).map(x => x * 2);
Lodash/Underscore 风格实现
_.mixin({
tap: function(obj, interceptor) {
interceptor(obj);
return obj;
}
});
// 使用示例
_.chain([1, 2, 3]).tap(console.log).map(x => x * 2).value();
主要应用场景
- 调试链式调用中间值
- 插入日志记录点
- 执行不影响主流程的副作用操作
注意:修改原生原型(如 Array.prototype)可能引起兼容性问题,建议使用独立函数或工具库实现。







