TS class类

class: 定义了一切事物的抽象特点

object:类的实例

面向对象oop的3大特征: 封装 、继承、 多态

封装: 将数据操作的细节隐藏起来, 只暴露对外的接口,外界调用端不需要也不可能知道细节,只能通过接口来访问该对象。

继承:子类继承父类  子类除了具有父类所有的属性之外,也具一些更具体的特性

多态: 由继承产生了不同的相关的类,对同一个方法有不同的响应 

//复习

class Animal {
constructor(name) {
this.name = name
}
run() {
return `${this.name} is running`
}
}

// const snake = new Animal('hky')
// console.log(snake.run())

// 继承  Animal 的  name 属性 和 run()方法
// class Dog extends Animal {
// bark() {
// return `${this.name} is barking`
// }
// }

// const xiaobao = new Dog('xiaobao')
// console.log(xiaobao.run()) // xiaobao is running
// console.log(xiaobao.bark()) // xiaobao is barking


// 多态 如果不写super
//报错原因是因为子类没有自己的 this 对象,而是继承父类的 this 对象,
//然后对其进行加工,而 super 就代表了父类的构造函数。super 虽然代表了父类 Person 的构造函数,
//但是返回的是子类 Son 的实例,即 super 内部的 this 指的是 Son。正确写法:

class Cat extends Animal {
static state = ['mammal']
constructor(name) {
super(name)
console.log(this.name, 'name') // maomao
}
run() {
return 'Meow, ' + super.run()
}
}

const maomao = new Cat('maomao')
console.log(maomao.run()) // Meow, maomao is running
console.log(Cat.state)

 

//Typescript中的类

Public 修饰的属性或者方法是共有的       默认是Public

Private 修饰的属性或者方法是私有的

Protected 修饰的属性或者方法是受保护的

 

class Animal {
readonly name: string // 只读
constructor(name) {
this.name = name
}
// private run() { // 私有的
// return `${this.name} is running`
// }
// protected run() { // 只有子类才能调用 不能在实例中调用
// return `${this.name} is running`
// }
run() {
return `${this.name} is running`
}
}
const snake = new Animal('lily')
// snake.name = 123 // => 报错 只读模式下不能修改
// console.log(snake.run()) 

class Dog extends Animal {
bark() {
console.log(this.name)
return `${this.name} is barking`
}
}
const xiaobao = new Dog('xiaobao')
console.log(xiaobao.run())
console.log(xiaobao.bark())

// class Cat extends Animal {
// static cate = ['hky']
// constructor(name) {
// super(name)
// console.log(this.name)

// }
// run() {
// return `Meow, ` + super.run()
// }
// }
// const maomao = new Cat('maomao')
// console.log(maomao.run())

// 类和接口的完美搭档

interface Radio {
switchVideo(trigger: boolean): void // 代表什么都不返回
}

interface Battery {
checkBatterys(): void
}
interface RadioWith extends Radio{
checkBatterys(): void
}
class Car implements Radio { // interface 契约的作用 告诉Car Cellphone 要实现这个方法
switchVideo(trigger: boolean) {

}
}

// class Cellphone implements Radio, Battery { // [ˈɪmplɪments] 使生效、贯彻、执行、实施
// switchVideo(trigger: boolean) {

// }
// checkBatterys() {

// }
// }

class Cellphone implements RadioWith { // 接口继承 RadioWith 有2个接口的方法 可以替代
switchVideo(trigger: boolean) {

}
checkBatterys() {

}
}

posted @ 2021-04-06 17:51  贺可英  阅读(648)  评论(0)    收藏  举报