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

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 {
...
}
}
主站蜘蛛池模板: 新化县| 闽侯县| 枝江市| 尉犁县| 炉霍县| 瑞丽市| 七台河市| 汪清县| 灵台县| 南澳县| 永清县| 县级市| 福贡县| 兰西县| 安塞县| 修水县| 五莲县| 忻城县| 辽阳市| 扶风县| 碌曲县| 德江县| 江都市| 汶川县| 聂拉木县| 衢州市| 平远县| 靖远县| 沧州市| 黑龙江省| 南京市| 姜堰市| 邯郸市| 东海县| 芮城县| 黎城县| 沙坪坝区| 高州市| 铜山县| 桃园市| 南木林县|