TypeScript 05-面向对象

53 阅读2分钟

一、类的定义

使用ES6的面向对象来开发

class Student{
    id:number
    name:string = "小黄"
    constructor(id:number,name:string){
        this.id = id;
        this.name = name
    }
    play(msg:string):void{
        console.log(123);
    }
}
new Student(1,"xiaowang").play("跑步")
export {}

类的属性必须要申明数据类型,还要初始化值。
定义行为时候,我们需要给行为函数设置参数,返回结果

静态属性和行为

class Student{
    id:number
    name:string
    static address:string = "武侯区"
    constructor(id:number,name:string){
        this.id = id;
        this.name = name
    }
    play(msg:string):void{
        console.log(123);
    }
    static eat(){
    }
}
new Student(1,"xiaowang").play("跑步")
Student.eat()
export {}

二、类的继承

class Animal{
    move(speed:number){
        console.log("能跑"+speed);
    }
}
class Dog extends Animal{
    constructor(){
        super()
    }
    move(){
    }
}
new Dog().move()

子类继承父类,子类写了构造函数,那就必须调用super,如果子类没有构造函数。默认调用
子类继承父类,子类重写父类的方法,优先调用子类自己的方法

三、访问修饰符

在TS中新增了访问修饰符。

可以对属性和行为进行修饰。你的属性就只能在指定的场景下使用 修饰符名字 作用 范围 private 私有类型 本类 protected 受保护类型 本类、子类 public 公共类型 本类、子类、类外部

class Animal{
    public type:string = "金毛"
    move(speed:number){
        console.log("能跑"+speed);
    }
}
class Dog extends Animal{
    private color:string = "黑色"
    constructor(){
        super()
    }
    move(){
        console.log(this.color);
        console.log(this.type);
    }
}
const dog = new Dog()
console.log(dog);
console.log(dog.type);

一般是给属性设置访问权限,比如定义一个people。

对于这个对象的某些属性我们不能直接暴露出去

女生年龄、身高、体重

class People{
    private idCard:string = "4384738437X"
    protected weight:string = "60kg"
    name:string = "xiaowang"
    // 获取内部私有变量的数据
    get getIdCard():string{
        //对身份证进行处理.把中间6位 * 来代替
        return this.idCard
    }
    //  获取外部的数据,修改内部的信息
    set setIdCard(val:string){
        // 判断身份是否有效
        this.idCard = val
    }
}
const res4 = new People()
console.log(res4.getIdCard);
// res4.setIdCard

ts提供的只读属性

public readonly name:string = "xiaowang"