【问题标题】:How to get the Class in constructor with typescript?如何使用打字稿在构造函数中获取类?
【发布时间】:2019-01-31 08:45:20
【问题描述】:

我尝试在实例化时将我的类的每个属性设置为空字符串。但是要获取所有属性,我需要获取在构造函数中实例化的“类”。任何帮助将不胜感激!

我使用 typescript 3.1

  • 任何想法如何在构造函数中获取类?
  • 或者我如何才能获得所有属性的列表,包括没有实例化的属性,仅在使用“this”而不是 Class 时?

这里是我用来获取类的所有属性的函数。

      Export class Base {
        id: String;
        ...

         constructor() {
           getAllProperties(MyClass) 
             // I would like to have MyClass to be dynamique
         }

      }

       function getAllProps(cls: new (...args: any[]) => any): any[] {   
         // return a list of all Class properties.
       }

我也尝试使用 Reflect.metadata API,但没有 Class 就无法获得任何好的结果。

【问题讨论】:

    标签: javascript typescript reflection prototype instantiation


    【解决方案1】:

    父构造器在子构造器之前被调用,因此它不起作用。你可以创建函数并在super()函数之后调用它

    // Parent
    class A1 {
        constructor() {
        }
    
        protected init() {
            //Get properties here
            console.log(this);
        }
    }
    
    // Child
    class A2 extends A1 {
        public a;
        public b;
    
        constructor() {
            super();
    
            this.a = 1;
            this.b = 2;
            //code here...
    
            this.init();
        }
    }
    

    【讨论】:

    • 感谢您的回复,但我不想像 this.a = "foo" 这样实例化属性。我正在做一个大项目,我想在父类中这样做。在您的示例中,启动每个子类中的所有属性会更容易。
    • 因此,也许您可​​以随时调用 this.init() 函数来查看子类的当前状态,也可以调用 setTimeout 与父构造函数的 0 延迟。
    • 如果没有类,我无法获得属性。 “this”没有给我不实例化的属性,它们不是可枚举的,所以this.foo = undefined。
    猜你喜欢
    • 2017-01-29
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2020-03-14
    • 2021-12-31
    相关资源
    最近更新 更多