Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Debugging 为什么创建双变量传递参数?_Debugging_Typescript - Fatal编程技术网

Debugging 为什么创建双变量传递参数?

Debugging 为什么创建双变量传递参数?,debugging,typescript,Debugging,Typescript,我有相同的模块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中,我有数组成分 ingr

我有相同的模块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变量?如何仅创建变量名称和金额?

您的构造函数正在创建这些属性,因为您将它们标记为
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){ }
}

你应该可以走了。该功能被称为参数属性,是

它的工作。我还有一个问题,若构造函数是创建公共属性的快捷方式,为什么我会在类中保留带有默认修饰符的变量,并在构造函数中使用public,它还会创建双变量?没问题。我不确定我是否理解第二个问题。如果在类主体和构造函数中都有相同的属性声明,则typescript编译器应抛出“重复属性”错误。