打字稿-console.log不显示对象属性

时间:2020-04-03 13:01:05

标签: typescript

我试图遍历对象的属性,但无法实现。

export class Test {
    public property1: string;
    public property2: number;

    test() {
        console.log(this);
        console.log(Object.getOwnPropertyNames(this));
    }
}

...

const t = new Test();
t.test();

console.log(this)不显示任何属性,因此,下面一行的迭代返回一个空数组。

为什么? (我也尝试过使用Object.keys(this))

编辑:最终目标是这样做:

export class MyObjectWithLessProperties {
    // lot of properties

    constructor(object: MyObjectWithMoreProperties) {
        Object.keys(this).forEach((key: string) => this[key] = object[key]);
    }
}

1 个答案:

答案 0 :(得分:0)

您尚未初始化属性值,因此期望它们为空。

这将按预期工作:

class Test {
    public property1: string = "test";
    public property2: number = 123;

    test() {
        console.log(this);
        console.log(Object.getOwnPropertyNames(this));
    }
}

const a = new Test();
a.test();

最好的方法是为Test类创建一个构造函数,并在创建新的Test()时将所需的值作为参数传递

示例:

class Test {
    private property1: String;
    private property2: number;

    constructor(property1: String, property2: number) {
        this.property1 = property1;
        this.property2 = property2;
    }

    test() {
        console.log(this);
        console.log(Object.getOwnPropertyNames(this));
    }
}

const a = new Test("test", 123);
a.test();