An abstract class
Abstract class: a class that can only be inherited but cannot be instantiated. It is an extension of TS to ES that defines abstract classes using abstract
abstract class Animal {
// Implement specific methods to facilitate subclass reuse
eat() {
console.log('eat')}// Declare abstract methods and let subclasses implement them
abstract sleep(): void
}
let animal = new Animal() // Failed to create instance
class Dog extends Animal {
constructor(name: string) {
super(a)this.name = name
}
name: string
run() {}
sleep() {
console.log('dog sleep')}}let dog = new Dog('wangwang')
dog.eat() // eat
Copy the code
The advantage of using abstract classes is that they can strip out commonalities, making it easier to reuse and extend code
polymorphism
Polymorphic: defines a method in a parent class, and has multiple implementations in subclasses that perform different operations on different objects while the program is running, implementing runtime bindings.
class Cat extends Animal {
sleep() {
console.log('cat sleep')}}let cat = new Cat()
let animals: Animal[] = [dog, cat]
animals.forEach(i= > {
i.sleep()
})
Copy the code
This polymorphism
class WorkFlow {
step1() {
return this
}
step2() {
return this}}new WorkFlow().step1().step2()
Copy the code
The polymorphism of this means that this can be either a parent type or a child type, ensuring that the parent and child interfaces call coherently
class Myflow extends WorkFlow {
next() {
return this}}new Myflow().next().step1().next().step2()
Copy the code