class 类

1. 什么是 class 类 : 定义了一切事物的抽象特点被称为 class 类
 
2. 对象 Object 是什么:  类的实例
 
3. 面向对象(OOP)三大特性: 
  封装 (对数据的一个操作,只暴露出 一个方法 或接口 外界不需要知道里面做了什么处理 )
  继承 (子类继承父类 子类拥有父类的所有特性外 还拥有其他的一些特性)
  多态 (多态是由继承而产生的不同的类 对同一个方法 有不同的响应)
 
 
1. 定义一个 class 类
 
class Pet{
  name:string;
  constructor(name:string){
   this.name = name
  }
  run(){
    return `${this.name} is runing`
  }
}
 
//new 一个实例 看看当前方法是否能进行输出
 
const  pig = new Pet("pig")
console.log(pig.run())
 
输出结果
 

 

 

2. 通过 extends 关键字来继承
 
class Mao extends Pet{
  bark(){
    return `${this.name} is barking`
  }
}
 
console.log(mao.bark());
console.log(mao.run());
 
输出结果

 

 

3. 重写构造函数 

重写构造函数 在子类中必须通过 super() 来调用父类的方法  来调用 不然会报错
 

class Can extends Pet{

  constructor(name:string){

    super(name)

    this.name = name

  }

  run(){

    return "Dog" + super.run()

  }

}

 

const dog = new Can("dog")

console.log(dog.run())

 

输出结果

 

 

 
posted @ 2021-11-02 16:54  虹猫淘气  阅读(123)  评论(0编辑  收藏  举报