Dha*_*hni 5 object-properties typescript
如何迭代类属性列表并获取每个属性的值(仅属性而不是函数)
class Person{
name:string;
age:number;
address:Address;
getObjectProperties(){
let json = {};
// I need to get the name, age and address in this JSON and return it
// how to do this dynamically, rather than getting one by one
// like json["name"] = this.name;
return json;
}
}Run Code Online (Sandbox Code Playgroud)
请帮忙。
如果您查看以下编译后的代码,您将无法做到这一点:
class Person {
name: string;
age: number;
address: Address;
}
Run Code Online (Sandbox Code Playgroud)
您会发现这些属性不属于其中:
var Person = (function () {
function Person() {
}
return Person;
}());
Run Code Online (Sandbox Code Playgroud)
仅当您分配一个值时才会添加该属性:
class Person {
name: string = "name";
}
Run Code Online (Sandbox Code Playgroud)
编译为:
var Person = (function () {
function Person() {
this.name = "name";
}
return Person;
}());
Run Code Online (Sandbox Code Playgroud)
您可以为此使用属性装饰器。
| 归档时间: |
|
| 查看次数: |
8477 次 |
| 最近记录: |