我有相同的模块ts
export class Ingredient {
public name: string;
public amount: number;
constructor(public pname: string, public pamount: number){
this.name = pname;
this.amount = pamount;
}
}
在comonen.ts中我有阵列成分
ingredients: Ingredient[] = [new Ingredient('Apples', 5),
new Ingredient('Apples', 5),
new Ingredient('Tomatoes', 2),
new Ingredient('Olives', 3),
new Ingredient('Onion', 4)
];
我调试并发现了类似的东西:
0:
Ingredient
pname:
Apples
pamount:
5
name:
Apples
amount:
5
我不明白为什么它创建了pname和name变量?如何只创建变量名称和金额?
答案 0 :(得分:1)
您的构造函数正在创建这些属性,因为您将它们标记为public
。
在构造函数中使用public
关键字本质上是一种创建公共属性的“快捷方式”,它是从构造函数参数自动分配的。所以代码:
export class Ingredient {
constructor(public pname: string, public pamount: number){
}
}
基本上相当于:
export class Ingredient {
public pname: string;
public pamount: number;
constructor(pname: string, pamount: number){
this.pname = pname;
this.pamount = pamount;
}
}
所以你真正想要的只是这个:
export class Ingredient {
constructor(public name: string, public amount: number){ }
}
你应该好好去。该功能称为参数属性,并且为well hidden in the official documentation.