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

Access modifiers

So far, all our class properties and methods have automatically had the public access modifier. This means they are available to interact with class instances and child classes. We can explicitly set the public keyword on our class properties and methods immediately before the property or method name:

class OrderDetail {
public product: Product;
public quantity: number;

public getTotal(discount: number): number {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
}

As you might have guessed, there is another access modifier, called private, which allows the member to only be available to interact with inside the class and not on class instances or child classes.

Let's look at an example:

  1. Let's add a delete method in our OrderDetail class, which sets a private deleted property:
class OrderDetail {
public product: Product;
public quantity: number;
private deleted: boolean;

public delete(): void {
this.deleted = true;
}
...
}
  1. Let's create an instance of OrderDetail and try to access the deleted property:
const orderDetail = new OrderDetail();
orderDetail.deleted = true;

As expected, the compiler complains:

There is a third access modifier, protected, which allows the member to be available to interact with inside the class and on child classes, but not on class instances.

主站蜘蛛池模板: 济宁市| 辰溪县| 乳山市| 大方县| 饶平县| 射洪县| 马鞍山市| 隆德县| 康定县| 锦州市| 武隆县| 翁源县| 手游| 同德县| 江北区| 南汇区| 达孜县| 正阳县| 吐鲁番市| 聊城市| 札达县| 根河市| 廉江市| 永福县| 洮南市| 景东| 会同县| 崇左市| 右玉县| 盘山县| 大同县| 邹平县| 金寨县| 婺源县| 洪洞县| 盐城市| 友谊县| 开鲁县| 镇安县| 榆林市| 秦皇岛市|