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

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 {
...
}
}
主站蜘蛛池模板: 平邑县| 剑川县| 金湖县| 泰兴市| 盐津县| 霸州市| 南城县| 桃江县| 澎湖县| 北海市| 长子县| 张家港市| 海阳市| 宣汉县| 芒康县| 麟游县| 英吉沙县| 香河县| 长白| 天镇县| 鹿泉市| 呼伦贝尔市| 怀宁县| 库伦旗| 沙湾县| 永靖县| 阿坝县| 广水市| 密山市| 女性| 镇巴县| 孙吴县| 革吉县| 崇明县| 旺苍县| 永吉县| 楚雄市| 巩义市| 肃北| 高青县| 卓尼县|