如何在装饰器中获取构造函数参数?

mx_code

我正在使用角度/打字稿。

如何在装饰器中获取构造函数参数?

以下是装饰器函数:

function ClassDecorator<T extends { new(...args: any[]): {} }>(constructor: T) {
    console.log("-- decorator function invoked --");
    return class extends constructor {

    }
}



并将其用作:

@ClassDecorator()
export class SomeClass {
constructor(arg1) {} // ----> I want to access this arg1 inside the ClassDecorator
}

所以我的问题是有没有访问的构造函数(这里的方式arg1)内部的争论@ClassDecorator

我尝试了一些类似于以下的解决方案:


export function ClassDec(ctor: Function) {
  ctor.prototype;
  console.log(' ctor.prototype :', ctor.prototype.arguments);
}


export function ClassDec(target: Function) {
  console.log(target.arguments);
  return (constructor: Function) => {
    console.log(constructor, target.arguments);
  };
}


// when I try to access the arguments of constructor function I'm getting an error saying cannot access arguments in strict mode.

但什么都没有解决!

这个想法很简单,我想constructor(arg1)在装饰器函数中接收参数,如下所示:

function ClassDecorator<T extends { new(...args: any[]): {} }>(constructor: T) {
    console.log("-- decorator function invoked --");

console.log(constructor.prototype.arguments)
    return class extends constructor {

    }
}



我知道这很难。我尝试了所有在线解决方案。请让我知道这是否可能。否则我可以放弃这个计划。

突出大脑

这对我有用(如代理):

    function ClassDecorator<T extends { new(...args: any[]): {} }>(constructor: T) {
        return class extends constructor {
            constructor(...args: any[]) {
                super(args);
                console.log(`Ctor arguments: ${args}`);
            }
        }
    }
    @ClassDecorator
    class SomeClass {
        constructor(arg1) {
    
        }
    }
    
    const a = new SomeClass("test");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在装饰器中获取参数名称

无法理解如何在装饰器内的包装函数中获取参数

在装饰器中获取 Python 函数参数的名称

如何在装饰器函数中打印函数默认参数?

如何在装饰器函数中访问类变量

如何在装饰器中比较更多参数?

如何在装饰器中获得Flask可选的URL参数?

Django - 如何在装饰器中访问请求正文?

如何在装饰器模式中处理“此”引用

如何在装饰器中捕获异常

如何获取在装饰器中调用装饰器的视图的URL?

如何在装饰器中使用上下文管理器以及如何将在装饰器中创建的对象传递给装饰函数

在Django中,如何在装饰器函数的请求对象中设置值并从装饰函数中的请求对象访问它

python wrapper函数在装饰器内部接受参数

如何在颤动中从构造函数中获取参数值?

如何仅在装饰器中处理* args和** kwargs并保持其他参数不变

如何在Dart中通过反射获取构造函数的参数?

如何在计算属性中获取构造函数参数

在装饰器中通过别名调用函数

在装饰器中访问原始函数变量

如何在装饰器中访问ngStyle键和值?

如何在装饰器中捕获多个相同类型的异常

如何避免硬编码呢?在装饰器中

如何通过装饰器获取底层函数参数信息?

如何评估从装饰器的包装器中调用的函数的参数?

在装饰器模式中,如何确保最低级别的元素不是装饰器?

在python的装饰器中包装构造函数

如何在继承的文件的装饰器函数中获取python文件名

如何在装饰器中注册其装饰的所有功能?