【问题标题】:Loop through class keys inside constructor?循环遍历构造函数中的类键?
【发布时间】:2019-04-03 15:11:43
【问题描述】:

假设我有一个巨大的类,我想通过执行某种逻辑来设置它的键的默认值

export class SomeClass {
    foo: number;
    bar: number;
    // gigantic list of key value pairs

    constructor(multiply) {
        const keys = Object.keys(this);
        keys.forEach((k, i) => keys[k] = i * multiply);
    }

Object.keys(this) 怎么会返回一个空数组? new SomeClass()怎么会返回一个空对象?

【问题讨论】:

  • 看起来你更喜欢使用列表而不是一个一个地定义参数
  • 改用key = value;

标签: javascript typescript class object


【解决方案1】:

TypeScript 不会编译未初始化的属性。例如:

class SomeClass {
    a: string
    b: number
}

... 将编译为该 JavaScript 代码:

var SomeClass = /** @class */ (function () {
    function SomeClass() {
    }
    return SomeClass;
}());

您可以使用TypeScript's Playground 进行尝试。

如果你想循环这些键,你必须初始化它们的所有值。例如,这将按您的意愿工作。

class SomeClass {
    a: string = '' // Initialise to an empty string.
    b: number = 0 // Initialise to 0.

    constructor() {
      console.log(Object.keys(this)) // => ['a', 'b']
    }
}

【讨论】:

    【解决方案2】:

    为了补充Mateusz Kocz 的答案,您可以使用undefined 初始化属性,甚至将属性定义放在构造函数之后。钥匙也会在那里。

    class NotInitialized {
        a: string;
        b: number;
    
        constructor() {
            logObjectKeys(this); // "NotInitialized" []
        }
    }
    
    class InitializedWithUndefined {
        a: string = undefined;
        b: number = undefined;
    
        constructor() {
            logObjectKeys(this); // "InitializedWithUndefined" ["a", "b"]
        }
    }
    
    class WithPropertyAfterConstructor {
        constructor() {
            logObjectKeys(this); // "WithPropertyAfterConstructor" ["a", "b"]
        }
    
        a: string = undefined;
        b: number = undefined;
    }
    
    new NotInitialized();
    new InitializedWithUndefined();
    new WithPropertyAfterConstructor();
    
    function logObjectKeys<T>(source: T) {
        console.log(
            Object.getPrototypeOf(source).constructor.name,
            Object.keys(source));
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2015-09-19
      • 2011-10-09
      • 2019-01-06
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多