TS: 基类抽象方法的定义

74 阅读1分钟

目的:定义抽象类方法,子类继承时确保抽象方法的this指向正确

实现:定义抽象方法时,第一个参数传入this

子类实现抽象方法时:

① 依然默认使用function的格式,但是在调用时必须使用bind绑定this

② 使用箭头函数的方式实现,调用时无需关注this指向。

abstract class Animal {
    name;
    constructor() {
        this.name = "animal";
    }
    // 核心:第一个参数指定传入this
    abstract eat(this: Animal, food: string): void;
}
// 默认情况,function方式实现
class Cat extends Animal {
    constructor() {
        super();
        this.name = "cat";
    }
    eat(this: Cat, food: string): void {
        console.log(`${this.name} eat  ${food}`);
    }
}
// 箭头函数,静态编译时确定this
class Dog extends Animal {
    constructor() {
        super();
        this.name = "Dog";
    }

    eat = (food: string) => {
        console.log(`${this.name} eat  ${food}`);
    }
}

const cat = new Cat();
cat.eat("fish");
const dog = new Dog();
dog.eat('bone');

function ohterFunc() {
    const { eat } = cat;
    console.log('other call cat function: ');
    eat.bind(cat)('rice')

    const { eat: dogEat } = dog;
    console.log('other call dog function: ');
    dogEat('milk');
}
ohterFunc()

运行结果:

image.png