TypeScript入门(三)

74 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第3天,点击查看活动详情

大家好,我是吃鱼的老鼠.最近在学习ts,有些心得来分享一下

在线练习网站

官方文档

三. 类

TS和js类似,都是通过class关键字来定义一个类.

1. 基本写法

class Dog1 {
    // 成员属性
    name: string
    // 构造函数
    constructor(name1: string) {  // name1相当于传入的参数
        this.name = name1
    }
    // 成员方法
    bark() {
        console.log(`${this.name1} is wangwang`)
    }
}

let smallDog = new Dog1('small')

2. extends(继承)和super关键字

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }

    run(speed: number = 0) {
        console.log(`${this.name} runs with speed ${speed}`)
    }
}

// Cat 继承了 Animal 的属性和方法(name和run())
class Cat extends Animal {
    age: number;
    constructor(name: string, age: number) {
        //我们正在构造我们自己的构造函数,那么我们必须调用 super,否则具有 this 的对象将不被创建
        super(name)
        this.age = age
    }
    // Cat 自己的方法
    fly(){
        console.log(`No matter how ${this.age} the cat is, it can't fly`)
    }
}
    let smallCat = new Cat('mixi',2)

    smallCat.fly()

3. public(公共),private(私有)与proteced(受保护)修饰符

public是默认的,可写肯不写

class Dog1 {
    public name: string
    public constructor(name1: string) {  
        this.name = name1
    }
    public bark() {
        console.log(`${this.name1} is wangwang`)
    }
}

private私有的(只能自己用),在类的外部使用会报错,子类也不能访问 例如:

class Dog2 {
    private name: string
     constructor(name: string) {  
        this.name = name
    }
}

new Dog2('kaka').name  // Property 'name' is private and only accessible within class 'Dog2'

image.png

protected在类的外部使用会报错,但子类可以继承

class Animal {
    protected name: string;
    protected constructor(name: string) {
        this.name = name;
    }
}

class Cat extends Animal {
    age: number;
    constructor(name: string, age: number) {
        super(name)
        this.age = age
    }

    fly() {
        console.log(`${this.name} 今年 ${this.age} 岁`)
    }
}

let animal1  = new Cat('hulu',2)  // 不报错

let anmimalName = new Animal('nana') //  Constructor of class 'Animal' is protected and only accessible within the class declaration.

image.png

这些就是TS中类的基本使用,更高阶的看 文档使用吧