在 angular 4 模型中,我有一些如下所示的 typescript 代码:
export class Thing {
public a: number;
public b: number;
public c: number;
constructor(a, b, c){
this.a = a || 0;
this.b = b || 0;
this.c = c || 0;
}
}
这似乎是一个明显的使用循环的地方,或者比声明变量 a、b 和 c 然后通过构造函数分配 a、b 和 c 更简单的东西。
但不确定如何完成。
最佳答案
您也可以这样做。在构造函数中通过访问修饰符 声明您的变量。这将使用该访问修饰符自动创建您的字段,并将您传递的值分配给它们。您也可以为参数分配默认值,如果传递的值是undefined
。
export class Thing {
constructor(public a: number = 0,
public b: number = 0,
public c: number = 0) {
}
}
const thing = new Thing(1, 2);
// thing.a = 1
// thing.b = 2
// thing.c = 0 - default value
一注也。 Angular 5发行了。你可以使用它。
关于javascript - 循环遍历 angular 4 (typescript) 构造函数中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48013992/