- 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.
推薦閱讀
- MySQL數(shù)據(jù)庫應用與管理 第2版
- Java從入門到精通(第5版)
- React.js Essentials
- Learn Swift by Building Applications
- Windows Server 2012 Unified Remote Access Planning and Deployment
- C語言程序設計實踐教程
- Java性能權威指南(第2版)
- 正則表達式經典實例(第2版)
- Spring核心技術和案例實戰(zhàn)
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(2)
- Test-Driven Machine Learning
- 零基礎學Kotlin之Android項目開發(fā)實戰(zhàn)
- 小程序,巧應用:微信小程序開發(fā)實戰(zhàn)(第2版)
- TMS320LF240x芯片原理、設計及應用
- Web前端應用開發(fā)技術