一 ts中的静态方法与静态属性
static
class Person{
name:string;
static age:number = 20; // 静态属性前加 static
constructor(name:string){
this.name = name
}
run(){
console.log(`${this.name}在运动`)
}
static print(){ //静态方法前加 static
console.log('静态方法调用')
console.log(`${this.name}在运动`) // undefined 无法取到name
console.log(`年龄${this.age}`)
}
}
var p = new Person('张三')
p.run() //张三在运动
Person.print() // 静态方法调用,年龄20
p.print() // 报错
二 ts中的多态
1.父类定义一个方法不去实现,让继承他的子类去实现,每一个子类有不同的表现
2.多态也是继承的一种表现,属于继承
class Animal{
name:string;
constructor(name:string){
this.name = name
}
eat(){
console.log('吃什么') //具体吃什么不知道,子类去实现,每一个子类表现不一样
}
}
class Dog extends Animal{
constructor(name:string){
super(name)
}
eat(){
return `${this.name}吃狗粮`
}
}
class Cat extends Animal{
constructor(name:string){
super(name)
}
eat(){
return `${this.name}吃猫粮`
}
}
二 ts中的抽象
1.ts中的抽象类是提供其他类继承的基类,不能直接被实例化
2.用abstract 关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现
3.abstract抽象方法只能放在抽象类里面
4.抽象类和抽象方法用来定义标准,标准: Animal 这个类要求他的子类必须包含eat方法
abstract class Animal{
public name:string;
constructor(name:string){
this.name = name
}
abstract eat():any; //抽象类的子类必须实现抽象类里面的抽象方法
}
class Dog extends Animal{
constructor(name:string){
super(name)
}
eat(){ // 子类必须有eat抽象方法
console.log(this.name + '吃狗粮')
}
}
var d = new Dog('大黄')
d.eat()
class Cat extends Animal{
constructor(name:string){
super(name)
}
eat(){ // 子类必须有eat抽象方法
console.log(this.name + '吃猫粮')
}
}
var c = new Dog('图图')
c.eat()








网友评论