- Learn React with TypeScript 3
- Carl Rippon
- 196字
- 2021-06-10 19:16:36
Static
Static properties and methods are held in the class itself and not in class instances. They can be declared using the static keyword before the property or method name.
Let's look at the following example:
- Let's make the getTotal method static on the OrderDetail class we have been using:
class OrderDetail {
product: Product;
quantity: number;
static getTotal(discount: number): number {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
}
- We get compilation errors where we try to reference the properties on the class. This is because the static method isn't in the class instance and therefore can't access these properties:
- To make the static method work, we can move its dependencies on the class instance to parameters in the function:
static getTotal(unitPrice: number, quantity: number, discount: number): number {
const priceWithoutDiscount = unitPrice * quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
- We can now call the static method on the class type itself, passing in all the parameter values:
const total = OrderDetail.getTotal(500, 2, 0.1);
console.log(total);
If we run the preceding program, we should get an output of 900 in the console.
推薦閱讀
- Java異步編程實戰
- 程序員數學:用Python學透線性代數和微積分
- RTC程序設計:實時音視頻權威指南
- Essential Angular
- Learning Neo4j 3.x(Second Edition)
- HTML5+CSS3+JavaScript Web開發案例教程(在線實訓版)
- Hands-On Functional Programming with TypeScript
- iOS開發實戰:從入門到上架App Store(第2版) (移動開發叢書)
- C專家編程
- Access 2010中文版項目教程
- IoT Projects with Bluetooth Low Energy
- Modernizing Legacy Applications in PHP
- 數據科學中的實用統計學(第2版)
- Web編程基礎:HTML5、CSS3、JavaScript(第2版)
- Python面向對象編程(第4版)