- Learn React with TypeScript 3
- Carl Rippon
- 212字
- 2021-06-10 19:16:36
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:
- 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;
}
...
}
- 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.
推薦閱讀
- 嵌入式軟件系統測試:基于形式化方法的自動化測試解決方案
- Pandas Cookbook
- 前端跨界開發指南:JavaScript工具庫原理解析與實戰
- Python神經網絡項目實戰
- 云計算通俗講義(第3版)
- Building a Quadcopter with Arduino
- Selenium Testing Tools Cookbook(Second Edition)
- 微服務從小白到專家:Spring Cloud和Kubernetes實戰
- Go語言開發實戰(慕課版)
- Hadoop 2.X HDFS源碼剖析
- Python預測分析實戰
- MongoDB Administrator’s Guide
- HTML5 Canvas核心技術:圖形、動畫與游戲開發
- Building Clouds with Windows Azure Pack
- Bitcoin Essentials