官术网_书友最值得收藏!

Constructors

Constructors are functions that perform the initialization of new instances of a class. In order to implement a constructor, we implement a function called constructor. It's common to set property values in the constructor to simplify consumption of the class.

Let's look at the following example:

  1. Let's create a constructor in the OrderDetail class that allows us to set the product and quantity:
class OrderDetail implements IOrderDetail {
product: Product;
quantity: number;

constructor(product: Product, quantity: number) {
this.product = product;
this.quantity = quantity;
}

getTotal(discount: number): number {
...
}
}
  1. If we create an instance of the class, we are forced to pass in the product and quantity:
const orderDetail = new OrderDetail(table, 2);
  1. This is nice because we've reduced three lines of code to one line. However, we can make our class even nicer to work with by making the default quantity parameter 1 if nothing is passed in:
constructor(product: Product, quantity: number = 1) {
this.product = product;
this.quantity = quantity;
}
  1. We now don't have to pass in a quantity if it is 1:
const orderDetail = new OrderDetail(table);
  1. We can save ourselves a few keystrokes and let the TypeScript compiler implement the product and quantity properties by using the public keyword before the parameters in the constructor:
class OrderDetail implements IOrderDetail {
constructor(public product: Product, public quantity: number = 1) {
this.product = product;
this.quantity = quantity;
}

getTotal(discount: number): number {
...
}
}
主站蜘蛛池模板: 旺苍县| 乌兰县| 即墨市| 黄梅县| 五莲县| 华阴市| 郸城县| 孝感市| 长海县| 揭西县| 大庆市| 隆安县| 尼木县| 新闻| 洛浦县| 格尔木市| 道孚县| 桦甸市| 惠水县| 繁峙县| 虞城县| 阳城县| 镇原县| 西乌珠穆沁旗| 灌阳县| 塔河县| 镇宁| 日喀则市| 山丹县| 鹤壁市| 万年县| 定襄县| 弥勒县| 石首市| 莱阳市| 靖州| 贵德县| 利川市| 鄯善县| 祁阳县| 牟定县|