一、静态属性和静态方法
1、回顾ES5中的静态方法
function Person(){
this.run2 = function () {}
}
Person.run = function (){}
Person.name = 'nihao'
Person.run()
let p = new Person()
p.run2()
2、TS 中定义静态方法和静态属性
class Person{
public name:string
static sex:string
constructor(name:string) {
this.name = name
}
run(){
console.log(this.name + "is running")
}
work(){
console.log(this.name + "is working")
}
static print(){
console.log("print", Person.sex)
}
}
Person.print()
let p = new Person('123')
p.run()
二、多态
1、定义:父类定义一个方法不去实现,让继承它的子类去实现,每一个子类有不同的表现。多态属于继承
class Animal{
name:string
constructor(name:string){
this.name = name
}
eat(){
console.log("eat 的方法")
}
}
class Dog extends Animal{
constructor(name:string){
super(name)
}
eat() {
console.log(this.name + '吃肉')
}
}
class Cat extends Animal{
constructor(name:string){
super(name)
}
eat() {
console.log(this.name + '吃🐟')
}
}
三、 抽象方法、抽象类
1、TypeScript 中的抽象类:它是提供其它类继承的基类,不能直接被实例化
2、用 abstract 关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现
3、abstract 抽象方法只能放在抽象类里面
4、抽象类和抽象方法用来定义标准。标准:Animal 这个类要求它的子类必须要包含 eat 方法
abstract class Animal{
name:string
constructor(name:string){
this.name = name
}
eat(){
console.log("eat 的方法")
}
abstract run():any
}
class Dog extends Animal{
constructor(name:string){
super(name)
}
eat() {
console.log(this.name + '吃肉')
}
run() {
console.log("正在奔跑")
}
}
let dog = new Dog("小狗狗")
dog.run()