官术网_书友最值得收藏!

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:

  1. 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;
}
}
  1. 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:

  1. 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;
}
  1. 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.

主站蜘蛛池模板: 玉田县| 林芝县| 马鞍山市| 盘锦市| 哈密市| 文水县| 枣阳市| 新乡县| 济宁市| 额尔古纳市| 屏南县| 五华县| 赫章县| 涪陵区| 青阳县| 章丘市| 香河县| 将乐县| 文山县| 台东县| 葫芦岛市| 卢氏县| 息烽县| 雷波县| 尖扎县| 中卫市| 盖州市| 高阳县| 怀远县| 铜山县| 四子王旗| 江永县| 清原| 临猗县| 阿图什市| 沙雅县| 九寨沟县| 凌海市| 大埔区| 巨野县| 水富县|