- 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.
推薦閱讀
- Web程序設計及應用
- 少兒人工智能趣味入門:Scratch 3.0動畫與游戲編程
- ReSharper Essentials
- 自己動手實現Lua:虛擬機、編譯器和標準庫
- HBase從入門到實戰
- FreeSWITCH 1.6 Cookbook
- Learning Informatica PowerCenter 10.x(Second Edition)
- SQL語言從入門到精通
- C/C++常用算法手冊(第3版)
- C語言從入門到精通(第4版)
- Magento 1.8 Development Cookbook
- Java EE 7 Development with NetBeans 8
- 微信小程序項目開發實戰
- Mastering Linux Network Administration
- Java:High-Performance Apps with Java 9