TypeScript|TypeScript Crash Course: Property Access Modifiers
There is no other great moment to head into the world of TypeScript instead of right now. Angular is in TypeScript, React is in TypeScript, and even Vue3 is in TypeScript. That means it's a skill we must equip with rather than wait and see.
This is the first post of my own TypeScript crash course, chances that it's your jam, stay tune;
)
public
, private
, protected
and readonly
access modifier
public
the default access modifier for propertiesprivate
lock the properties inside the cage, no one else except the class in where it's defined can access it. But we could approach it in JavaScript runtime, even byvalueOf
method.protected
as the same asprivate
, but open a backdoor for derived class.readonly
the properties marked withreadonly
should be initialized either when declare in no time or insideconstructor
. But it only works in TypeScript.
/* compile time */ class User { readonly idCard: string constructor(idCard: string) { this.idCard = idCard } }let user = new User('123') user.idCard = '321' // error hint/* runtime */ user.idCard = '321' console.log(user.idCard) // "321", the value of idCard has been changed.// solution for real readonly propertiesclass User { readonly idCard: string constructor(idCard: string) { this.idCard = idCard Object.defineProperty(this, 'idCard', { writable: false }) } } /* runtime */ user.idCard = '321' // everything goes well console.log(user.idCard) // but it's still "123"
class User {
private readonly idCard: string
protected name: string
age: numberconstructor(idCard: string, name: string, age: number) {
this.idCard = idCard
this.name = name
this.age = age
}
}
Fortunately, TypeScript has done that for us. When we specify
public
, private
or other access modifiers on the constructor parameters, a corresponding property is created on the class and filled with the value of the parameter. So we could make the previous one much damn shorter like this.class User {
constructor(private readonly idCard: string, protected name: string, public age: number) {}
}
Pretty cool yet; )
推荐阅读
- 深入理解|深入理解 Android 9.0 Crash 机制(二)
- typeScript入门基础介绍
- 带你了解类型系统以及flow和typescript的基本使用
- react+typescript+router框架搭建笔记
- typeScript+koa2+eslint搭建完整nodejs开发环境(自建脚手架)
- Android|莫名Crash---目睹Baidu地图API之怪现象一
- 02.Android崩溃Crash库之App崩溃分析
- vue|vue + typescript(一)配置篇
- vite+vue3+typescript+pnpm-workspace-monorepo 项目搭建记录
- TypeScript基础学习(4): 类