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

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.

主站蜘蛛池模板: 平利县| 锡林浩特市| 鱼台县| 洛川县| 庆阳市| 枣强县| 双辽市| 长泰县| 永丰县| 探索| 额济纳旗| 五常市| 镇宁| 冷水江市| 射阳县| 崇文区| 金山区| 鄂托克前旗| 贵州省| 句容市| 新津县| 彰化市| 峡江县| 永兴县| 湘乡市| 武功县| 巴里| 施秉县| 昌都县| 彰化市| 曲水县| 伊川县| 广南县| 屏山县| 通州区| 酒泉市| 密云县| 阿合奇县| 博客| 陇川县| 新郑市|