先看ES6中一个简单的类
class Greeter { greeting: string constructor(msg: string){ this.greeting = msg } greet(){ return 'hello ' + this.greeting } } let greeter = new Greeter('world!') console.log(greeter.greet())//hello world!
简单的继承
//简单的继承 class Animal { move(distince: number=0){ console.log(`The animal move ${distince} m`) } } class Dog extends Animal { bark() { console.log('woof! woof!') } } const dog = new Dog() dog.bark()//woof! woof! dog.move(12)//The animal move 12 m
稍微复杂一点的继承
class Animal { name: string constructor(name) { this.name = name } move(distance: number){ console.log(`${this.name} is move ${distance} m`) } } class Snake extends Animal { constructor(name: string){ super(name) } move(distance: number=10){ console.log('Slithering...') super.move(distance) } } class Horse extends Animal { constructor(name: string){ super(name) } move(distance: number = 35){ console.log('Gallophing...') super.move(distance) } } let sam = new Snake('sam') let tommy: Animal = new Horse('tommy') sam.move() tommy.move(38) // Slithering... // sam is move 10 m // Gallophing... // tommy is move 38 m
2019-05-24 15:57:48