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

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 {
...
}
}
主站蜘蛛池模板: 怀仁县| 徐州市| 文山县| 尤溪县| 临澧县| 拜城县| 张北县| 故城县| 梨树县| 稷山县| 扎赉特旗| 辽源市| 大港区| 社会| 卢湾区| 定西市| 石家庄市| 五指山市| 嵊泗县| 石景山区| 铜川市| 祁东县| 望奎县| 龙陵县| 新余市| 峨边| 栾川县| 西吉县| 张家港市| 从化市| 镇坪县| 汉寿县| 湘潭市| 彝良县| 西充县| 天全县| 仪陇县| 洪江市| 仁怀市| 射洪县| 鄄城县|