如何在类构造函数或方法中自动传递调用方作用域属性作为参数
需求实现可行性说明
这个需求可以实现,不需要修改现有子类的调用代码,生产环境推荐使用上下文传递方案,以下是具体实现逻辑:
方案1:运行时上下文自动传递(生产可用)
利用全局临时变量存储当前执行的实例ID,BaseClass自动为所有子类方法包裹上下文代理,在构造函数和method执行时自动读取调用方ID,执行结束后恢复上下文避免污染。
完整实现代码如下:
// 全局运行时上下文,存储当前执行的调用方ID const executionContext = { currentCallerId: null } abstract class BaseClass { protected id; // 存储调用方实例ID public callerId; constructor() { // 实例化时直接读取当前上下文的调用方ID this.callerId = executionContext.currentCallerId; // 自动代理子类所有实例方法,自动绑定执行上下文 const proto = Object.getPrototypeOf(this); Object.getOwnPropertyNames(proto).forEach(methodName => { if (methodName === 'constructor' || typeof this[methodName] !== 'function') return; const originalFn = this[methodName]; this[methodName] = (...args) => { const prevCallerId = executionContext.currentCallerId; executionContext.currentCallerId = this.id; try { return originalFn.apply(this, args); } finally { // 方法执行完恢复上下文,避免链式调用出错 executionContext.currentCallerId = prevCallerId; } } }) } method() { // 此处可直接拿到正确的callerId console.log(`实例ID:${this.id},调用方ID:${this.callerId}`); } } // 子类完全不需要修改原有代码 class ChildClass extends BaseClass { id = 'ChildId'; } class ParentClass extends BaseClass{ id = 'ParentId'; parentMethod() { // 原有调用逻辑不变,不需要手动传参 new ChildClass().method() } } // 测试调用 new ParentClass().parentMethod(); // 输出:实例ID:ChildId,调用方ID:ParentId
异步场景适配
如果存在异步逻辑,浏览器环境可以引入zone.js处理异步上下文传递,Node.js环境可以使用内置的AsyncLocalStorage替换全局变量,就能保证异步逻辑里的上下文不会错乱。
方案2:调用栈解析(仅适合调试用)
通过临时抛出Error解析调用栈信息,映射到对应的调用方实例ID,不需要修改任何现有逻辑,但压缩打包后调用栈会失效,不适合生产环境使用。
内容的提问来源于stack exchange,提问作者Yorgos Kakavas
相关产品推荐
相关产品推荐

