- 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 {
...
}
}
推薦閱讀
- Python程序設計教程(第2版)
- Spring 5.0 Microservices(Second Edition)
- Linux C/C++服務器開發實踐
- Learning Docker
- Django開發從入門到實踐
- OpenNI Cookbook
- Learning Firefox OS Application Development
- C++程序設計基礎教程
- Unity 5 for Android Essentials
- Geospatial Development By Example with Python
- JavaScript程序設計(第2版)
- Red Hat Enterprise Linux Troubleshooting Guide
- Getting Started with Python
- Windows Phone 8 Game Development
- Mastering Elixir