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

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.

主站蜘蛛池模板: 广东省| 乃东县| 长宁区| 五华县| 安乡县| 安溪县| 舒兰市| 忻州市| 遵义县| 微山县| 昌平区| 湘潭市| 定兴县| 南丹县| 巨鹿县| 新野县| 县级市| 准格尔旗| 克拉玛依市| 张家川| 芜湖市| 宁南县| 维西| 广宗县| 牡丹江市| 弋阳县| 祁阳县| 凌云县| 湘潭县| 浏阳市| 金寨县| 天气| 阿克陶县| 浮山县| 思茅市| 柳州市| 苍南县| 江都市| 鹤岗市| 手游| 延安市|