- Learn React with TypeScript 3
- Carl Rippon
- 241字
- 2021-06-10 19:16:35
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:
- 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 {
...
}
}
- If we create an instance of the class, we are forced to pass in the product and quantity:
const orderDetail = new OrderDetail(table, 2);
- 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;
}
- We now don't have to pass in a quantity if it is 1:
const orderDetail = new OrderDetail(table);
- 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 {
...
}
}
推薦閱讀
- 基于Java技術的Web應用開發
- Responsive Web Design with HTML5 and CSS3
- INSTANT CakePHP Starter
- Python王者歸來
- Spring實戰(第5版)
- 從0到1:Python數據分析
- jQuery炫酷應用實例集錦
- Learning JavaScript Data Structures and Algorithms(Second Edition)
- Microsoft Dynamics GP 2013 Cookbook
- Python高性能編程(第2版)
- 深度學習:基于Python語言和TensorFlow平臺(視頻講解版)
- Vue.js項目開發實戰
- PHP程序員面試算法寶典
- MATLAB/Simulink與過程控制系統仿真
- Mastering Microsoft Dynamics AX 2012 R3 Programming