es6来实现封装、继承学习

一、为什么要封装

  在开发过程中,具有相同处理逻辑的代码通常会进行函数的封装来减少代码冗余,使代码看起来更加美观,

  属性一般定义在构造函数中,而方法一般定义在prototype原型上

es6中的class类的实现

class Computer{
  constructor(size,color,cpu){
    this.size=size;
    this.color=color;
    this.cpu=cpu;
  }
  playVideo(){
    console.log('播放功能');
  }
  writeWord(){
    console.log('编写功能');
  }
}
const windowComputer=new Computer('2131','red','aaaa');
windowComputer.playVideo();
windowComputer.writeWord();

在类里面定义方法,是直接定义在原型上的。constructor方法相当于es5中构造函数本身,类被实例化之后(使用new 运算符之后)作用域和this指向将赋给新的实例对象。

二、什么是继承

当现有构造函数(类)属性和方法是自身所需要的但还不能满足自身的要求时,这时候就需要继承了,然后定义自身特有的一些属性或方法

用es6的class类实现继承

class Computer {
  constructor(screenSize, color, cpu){
    this.screenSize = screenSize
    this.color = color
    this.cpu = cpu
  }
  playVideo(){
    console.log('我具有播放音视频的功能')
  }
  writeWord(){
    console.log('我具有编辑文稿的功能')
  }
}
//使用extends关键字 deskTypeComputer 继承 Computer
class deskTypeComputer extends Computer{
  constructor(screenSize, color, cpu,crateLong, crateWidth, crateHeight){
    //继承父类的属性,super要放在第一行
    super(screenSize, color, cpu)
    //定义自己的属性
    this.crateLong = crateLong
    this.crateWidth = crateWidth
    this.crateHeight = crateHeight
  }
}
//生成的普通window电脑实例
const windowComputer = new Computer('1320*768', 'black', 'i5')
windowComputer.playVideo();//我具有播放音视频的功能
console.log(windowComputer.screenSize)//1320*768
console.log(windowComputer.color)//black
console.log(windowComputer.cpu)//i5
 
//生成window台式电脑实例
const windowDeskTypeComputer = new deskTypeComputer('1960*1280', 'white', 'i7', '50cm', '24cm', '55cm');
windowDeskTypeComputer.writeWord();//我具有编辑文稿的功能
console.log(windowDeskTypeComputer.screenSize)//1960*1280
console.log(windowDeskTypeComputer.color)//white
console.log(windowDeskTypeComputer.cpu)//i7
console.log(windowDeskTypeComputer.crateLong)//50cm
console.log(windowDeskTypeComputer.crateWidth)//24cm
console.log(windowDeskTypeComputer.crateHeight)//55cm

原文链接:https://blog.csdn.net/m0_37792354/article/details/82500471

猜你喜欢

转载自www.cnblogs.com/chao202426/p/11451149.html