- 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.
推薦閱讀
- 玩轉(zhuǎn)Scratch少兒趣味編程
- Python科學(xué)計(jì)算(第2版)
- Node.js 10實(shí)戰(zhàn)
- 編程珠璣(續(xù))
- 從0到1:HTML+CSS快速上手
- Blockly創(chuàng)意趣味編程
- Java持續(xù)交付
- Python數(shù)據(jù)分析(第2版)
- 軟件架構(gòu):Python語言實(shí)現(xiàn)
- SQL Server與JSP動態(tài)網(wǎng)站開發(fā)
- C和C++游戲趣味編程
- C++寶典
- 零基礎(chǔ)學(xué)Kotlin之Android項(xiàng)目開發(fā)實(shí)戰(zhàn)
- Visualforce Developer’s guide
- Machine Learning for OpenCV