- 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.
推薦閱讀
- iOS面試一戰到底
- Learning C# by Developing Games with Unity 2020
- 數字媒體應用教程
- Getting started with Google Guava
- 高效微控制器C語言編程
- 移動界面(Web/App)Photoshop UI設計十全大補
- Node.js全程實例
- Java EE核心技術與應用
- 運用后端技術處理業務邏輯(藍橋杯軟件大賽培訓教材-Java方向)
- Spring Boot+Vue全棧開發實戰
- Web前端應用開發技術
- 深度探索Go語言:對象模型與runtime的原理特性及應用
- Python+Office:輕松實現Python辦公自動化
- Python編程基礎教程
- 深入淺出 HTTPS:從原理到實戰