如何在方法装饰器Action中获取类装饰器Controller设置的__id属性
问题原因
首先要明确装饰器的执行顺序:方法装饰器的执行时机早于类装饰器,所以Action装饰器运行时,Controller类装饰器还没有给类构造函数挂载__id属性,直接在Action的返回函数中同步取值是拿不到结果的。
可行解决方案
方案1:方法调用时延迟取值
你可以在方法实际被调用的时候再获取所属类的__id,此时类装饰器已经执行完成,__id已经完成挂载:
function Action (options) { return function (target: any, propertyKey: string) { const originalMethod = target[propertyKey] // 重写原方法,加入取值逻辑 target[propertyKey] = function (...args) { // 方法调用时this指向类实例,实例的constructor就是被Controller装饰过的类构造函数 const classId = this.constructor.__id // 这里就可以用拿到的classId做后续逻辑 console.log('所属类ID:', classId) return originalMethod.apply(this, args) } } }
方案2:类装饰器中统一关联ID
你可以先让Action装饰器只负责收集方法元数据,等到类装饰器执行、__id生成后,再统一给所有方法关联类ID:
// Action装饰器仅收集路由元数据 function Action (options) { return function (target: any, propertyKey: string) { if (!target.__actionMeta__) target.__actionMeta__ = [] target.__actionMeta__.push({ path: options, methodName: propertyKey }) } } // Controller装饰器生成ID后统一关联 function Controller (options) { return function(target: any) { const id = uuid(); target.__id = id; pushInASet(id, target) // 遍历所有收集到的Action元数据,关联ID if (target.prototype.__actionMeta__) { target.prototype.__actionMeta__.forEach(action => { action.classId = id // 也可以在这里直接完成路由注册等逻辑 }) } } }
内容的提问来源于stack exchange,提问作者vivekfyi
相关产品推荐
相关产品推荐

