-
public
:類外可見(jiàn)(默認(rèn)就是public
),類內(nèi)及子類也都可訪問(wèn)
-
private
:僅類內(nèi)可見(jiàn),this.xxx,但類型擦除后,如果人家用js引用,還是可以訪問(wèn),因此ts提供了#var
作為真正的私有屬性
-
protected
:類內(nèi)及子類可見(jiàn),類似于整個(gè)家族類
可見(jiàn)
class Person {
friend?: Person // 默認(rèn)是public
protected gender = 'male'
private height = 170
public weight = 70
#age = 20 // 真正的私有屬性(private)
constructor(public name:string,friend?:Person){
this.friend = friend
this.name = name
this.#age = 20
}
sayHi(){
console.log(this.name)
}
getHeight(){
console.log(this.height)
console.log(this.name)
console.log(this.gender)
}
}
const p = new Person('frank')
p.sayHi()
p.getHeight()
class User extends Person{
declare friend?: User
constructor(name:string,friend?:User){
super(name,friend)
}
test(){
console.log(`---${this.gender}---`)
console.log(`---${this.weight}---`)
// 不能訪問(wèn) this.height
}
}
const u1 = new User('mike')
u1.test()
u1.weight
// 不能訪問(wèn) u1.gender 以及 u1.height
-
static
:靜態(tài)屬性,就是類自身的屬性,類似于原型中的共有屬性
的概念
class Student {
static grade = 7 // 可修改
static readonly tag = '' // 不能修改
}
Student.grade = 8
- 注意點(diǎn):靜態(tài)屬性不能聲明
name
,因?yàn)閏lass在js中就是函數(shù)
:class A {}; typeof A === 'function'
,而所有的函數(shù)都有name
屬性
- 類和泛型
class Hash<K,V> extends Map<K,V> {
destroy(){
this.clear() // 繼承自Map類的方法
}
}
- 匿名類
-
abstract
:抽象類,可以不實(shí)現(xiàn)一部分屬性。不能創(chuàng)建實(shí)例
- 把類當(dāng)做參數(shù):
class Person {
constructor(public name:string){}
}
function f(X:typeof Person){
const p = new X('frank')
console.log(p.name)
}
f(Person)
// 這不是箭頭函數(shù),箭頭函數(shù)是不能加 new 的
function f2(X: new (name:string) => Person){
const p = new X('ricky')
console.log(p.name)
}
f2(Person)