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

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.

主站蜘蛛池模板: 仁寿县| 铁岭县| 同心县| 太仆寺旗| 黄浦区| 溧阳市| 石台县| 灌南县| 屏东市| 长沙县| 高淳县| 洱源县| 磐安县| 阿勒泰市| 阆中市| 张北县| 安仁县| 肇东市| 贺兰县| 临海市| 德庆县| 瓦房店市| 丁青县| 望奎县| 怀集县| 南木林县| 霍林郭勒市| 呈贡县| 萝北县| 甘德县| 阳城县| 汝州市| 罗平县| 古蔺县| 南澳县| 海安县| 北川| 甘南县| 闵行区| 黑山县| 盐城市|