遍历构造函数内部的类键?

时间:2019-04-03 15:11:43

标签: javascript typescript class object

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

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()如何返回一个空对象?

2 个答案:

答案 0 :(得分:2)

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']
    }
}

答案 1 :(得分:0)

要补充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));
}