typescript - 打字稿-console.log 不显示对象属性
问题描述
我正在尝试遍历对象属性,但无法实现。
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]);
}
}
解决方案
您尚未初始化属性值,因此它们应该为空。
这将按预期工作:
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 类创建一个构造函数,并在创建 new 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();