类和对象

对象是类的实例化
类是对象的抽象集合

类结构:

class 类名 {
    字段声明,需要默认初始值或者在构造器内初始化
    构造方法, 只有一个
    普通方法,无需function修饰
    静态成员,static 修饰的字段/方法/代码块(类加载时被执行,且只有一个),通过类访问,不通过对象访问
}

权限修饰符

  • public
  • private
  • protected 外部无法访问,子类和内部可以访问

继承

Class 子类 extends 父类 {
    
}

子类可以拥有父类非私有的属性和方法
子类可以重写父类的方法

多态

  • 静态多态,目前只支持基础数据类型,不支持对象入参
  • 动态多态, 通过方法的重载实现多态
Class Father {
    getAge(){
        return 60;    
    }
}

Class SonOne extends Father {
    getAge() {
        return 40;    
    }
}

Class SonTwo extends Father {
    getAge() {
        return 20;    
    }
}

Class card {
    logAge(person: Father) {
        person.getAge    
    } 
}

//使用
son:Father = new SonOne()
sonTwo:Father = new SonTwo()
cardA:card = new card()
//通过重写实现多态
cardA.logAge(son)
cardA.logAge(sonTwo)

单例模式

Class netManager {
    //staic修饰,通过类直接访问,生成对象
    // private修饰,外部无法直接访问instance对象
    private static instance = new netManager()
    // 外部通过方法获取单例对象
    static getInstance() {
        return netManager.instance    
    }
    
    //可选
    //private修饰构造器方法,外部无法创建对象
    private constructor() {
            
    }
}

//可释放的单例
Class netManager {
    //staic修饰,通过类直接访问,生成对象
    // private修饰,外部无法直接访问instance对象
    private static instance:netManager|null = null
    // 外部通过方法获取单例对象
    static getInstance() {
        if (netManager.instance == null) {
            netManager.instance = new netManager()        
        }
        return netManager.instance    
    }
    
    static releaseInstance() {
        netManager.instance = null    
    }
    
    //可选
    //private修饰构造器方法,外部无法创建对象
    private constructor() {
            
    }
}

泛型

// 基础数据类型的泛型使用
Class Person<T> {
    data:T[]
}

son:Person = new Person<number>()

//自定义数据类型的泛型使用
Class Child {
    
}

Class Student extends Child {
    
}

Class Teacher<T extends Clild> {
    data:T[]
}

person:Teacher = Teacher<Student>()

作为入参,定义类内泛型的类型,基础数据类型直接使用<T>  自定义数据类型使用
<T extends Class> 可以使用其指定Class及其子类

function getArrLast<T>(arr:<T>[]):T{
    return arr[arr.length - 1]
}
//方式一
res:number = getArrLast([1,2,3])
//方式二
res:string = getArrLast<string>(['1','2','3'])

泛型方法,泛型取决与入参时参数的类型,即arr:<T>[]

空值安全

  • 联合类型 判空
let x: number | null = null
//使用 !进行空判断 非空断言判断符 x为空时不参与计算
let y: number
y = x! + 1
// 空值合并运算符 类似三元运算符
let a: string | null = null
let b = a ?? ''
consloe.log(b)
  • 关联对象判空
// 使用?处理关联对象a为undefind,为空时不回调用对应methodA方法,保护空对象
Class A {
    methodA() {            
    }
}
Class B {
    a?:ClassA
}

b:ClassB = new ClassB()
b.a?.methodA()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容