类
来个简单的栗子:
class Person{
name: string;
constructor(name:string){
this.name = name
}
todo():void{
console.log(`${this.name}.....`)
}
}
let xiaoming = new Person("小明")
我们声明了一个Person
的类,他有三个成员:属性name
、一个构造函数、一个todo
的方法,
我们使用 new
构造了 Person
类的一个实例。 它会调用之前定义的构造函数,创建一个 Greeter
类型的新对象,并执行构造函数初始化它
继承
class Person{
name: string;
constructor(name:string){
this.name = name
}
todo():void{
console.log(".....")
}
}
class Age extends Person{
age:number;
constructor(name:string,age:number){
super(name)
this.age = age
}
getPeople():string{
return `${this.name}年龄:${this.age}`
}
}
let xiaoMing = new Age("小明",18)
xiaoMing.todo()
console.log(xiaoMing.getPeople())
这里Age
是个派生类,他派生自Person
基类,通过extends
关键字,派生类通常称为 子类, 基类通常称为 超类
Age
继承了Person
,我们构建了一个Age
的实例,它能够使用todo
,getPeople
两个方法
公共,私有与受保护的修饰符
- 公共(
public
)
在ts
中类成员默认是public
,当然也可以明确的将一个成员标记成public
,如下:
class Person{
public name: string;
public constructor(name:string){
this.name = name
}
public todo():void{
console.log(`${this.name}.....`)
}
}
- 私有(
private
)
当成员标记了private
,声明了这个类的外部无法访问
class Person{
private name: string;
constructor(name:string){
this.name = name
}
public todo():void{
console.log(`${this.name}.....`)
}
}
let xiaoming = new Person("xiaoming")
xiaoming.name //报错 属性“name”为私有属性,只能在类“Person”中访问
- protected
protected
修饰符和private
修饰符行为相似,但是protected
在派生类中可以访问
//private
class Person{
private name: string;
constructor(name:string){
this.name = name
}
public todo():void{
console.log(`${this.name}.....`)
}
}
class Age extends Person {
age:number;
constructor(name:string,age:number){
super(name)
this.age = age
}
getInfor():void{
console.log(`${this.name},${this.age}`) //报错 属性“name”为私有属性,只能在类“Person”中访问
}
}
// protected
class Person{
protected name: string;
constructor(name:string){
this.name = name
}
public todo():void{
console.log(`${this.name}.....`)
}
}
class Age extends Person {
age:number;
constructor(name:string,age:number){
super(name)
this.age = age
}
getInfor():void{
console.log(`${this.name},${this.age}`)
}
}
let xiaoming = new Age("xiaoming",18)
xiaoming.name //报错 属性“name”受保护,只能在类“Person”及其子类中访问
我们不能在 Person
类外访问name
,但是我们可以在Age
类内访问,因为Age
类是派生自Person
构造函数也可以被标记成 protected
,这就意味着这个类不能在包含他的类外实例,但是可以继承
class Person{
protected name: string;
protected constructor(name:string){
this.name = name
}
public todo():void{
console.log(`${this.name}.....`)
}
}
class Age extends Person {
age:number;
constructor(name:string,age:number){
super(name)
this.age = age
}
getInfor():void{
console.log(`${this.name},${this.age}`)
}
}
let xiaoming = new Age("xiaoming",18)
let xiaoming1 = new Person("xiaoming") //报错 类“Person”的构造函数是受保护的,仅可在类声明中访问
readonly只读
只读属性,必须在声明时候或者在构造函数中初始化
class Person{
readonly name: string;
readonly age: number = 18;
constructor(name:string){
this.name = name
}
todo():void{
this.name = "xiaohua" //报错 无法分配到 "name" ,因为它是只读属性
}
}
let xiaoming = new Person("xiaoming")