- 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 {
...
}
}
推薦閱讀
- Learning Neo4j
- Modular Programming with Python
- 軟件架構設計:大型網站技術架構與業務架構融合之道
- 跟老齊學Python:輕松入門
- Getting Started with SQL Server 2012 Cube Development
- Oracle JDeveloper 11gR2 Cookbook
- HTML 5與CSS 3權威指南(第3版·上冊)
- Instant PHP Web Scraping
- Citrix XenServer企業運維實戰
- Mastering AWS Security
- Orchestrating Docker
- HTML5+CSS3+jQuery Mobile APP與移動網站設計從入門到精通
- C編程技巧:117個問題解決方案示例
- SQL Server 2012 數據庫應用教程(第3版)
- Android應用程序設計