2017-07-01 82 views
0

我具有相同模块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和名称可变我不明白?如何才能创建变量名称和金额?

回答

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.

+0

它的工作表示感谢。我还有一个问题,如果构造函数是创建公共属性的快捷方式,为什么如果我将在类中使用默认修饰符变量,并在构造函数中使用公共,它也创建双变量? –

+0

没问题。我不确定我是否理解这第二个问题。如果在类的主体和构造函数中都有相同的属性声明,那么typescript编译器应该引发“重复属性”错误。 –