ES5和ES6中的类与继承

何为继承

说白了就是让对象之间产生联系

ES5中的继承

ES5中的继承思想是这样

  • 使用函数作为类
  • 类作为模板
  • 根据模板制造出的东西叫对象实例
  • 对象实例拥有和类一样的东西
  • 类的属性直接写在类中
  • 函数也可以写在类中
  • 函数太多,每个实例继承的属性可能不一样,但是行为是一致
  • 所以把行为从类中抽离
  • 把行为放到公共区域
  • 这个区域就是类这个方法上的原型里面
  • 使用prototype进行继承
//使用函数作为类
function Animal(name,age){
    
    
  //把属性放类中
  this.name = name 
  this.age = age
}
//把方法放在类的原型上
Animal.prototype.eat = function(){
    
    
  console.log(`${
      
      this.name} is eating`)
}

//子类继承父类
function Cat(name,age,color){
    
    
  Animal.call(this,name,age)
  this.color = color
}
Cat.prototype = new Animal()
Cat.prototype.constructor = Cat
//实例化对象
let cat = new Cat('小猫','2','black')
console.log(cat)
console.log(cat.eat())

ES5中的类的静态属性和方法

就是方法不挂在公共区域,而是挂载到类上,这样不会被继承,也不能通过实例的对象进行调用。

//定义
function Animal(name,age){
    
    
  //把属性放类中
  this.name = name
}
//静态属性
Animal.sex = 'female'

//静态方法
Animal.getSex = function(){
    
    
  console.log('这只动物是雌性的')
}

//调用
console.log(Animal.sex)
Animal.getSex()

ES6中的继承

ES5中的继承思想是这样

  • 使用class声明类
  • 类作为模板
  • 根据模板制造出的东西叫对象实例
  • 对象实例拥有和类一样的东西
  • 类的属性直接写在类的构造方法中
  • 函数也写在类中
  • 使用extends继承
  • 使用super继承属性
class Animal {
    
    
    //把属性放类的构造函数中
    constructor(name,age){
    
    
      this.name = name 
      this.age = age
   }
    //直接写方法
    eat(){
    
    
       console.log(`${
      
      this.name} is eating`)
    }
}

//使用extends继承,属性继承使用super,方法直接默认,不需要额外操作
class Cat extends Animal{
    
    
   constructor(name,age,color){
    
    
      super(name,age)
      this.color = color
   }
}
//实例化对象
let cat = new Cat('小猫','2','black')
console.log(cat)
console.log(cat.eat())

ES6中类的静态方法和属性

和es5一样

ES6中类的私有属性

和之前的对象中的私有属性一模一样,使用getter与setter

//隐藏真正的属性_age,只能访问age这个接口,每次修改必须经过set
let _age = 18
class People {
    
    
  constructor(name,sex){
    
    
    this.name = name
    this.sex = sex
    this.age = _age
  }
  set age(val){
    
    
    if(val < 25 && val>0){
    
    
      _age = val
    }
  }
  get age(){
    
    
    return _age
  }
}

let people = new People('小明','男')
console.log(people) 
people.age = 12
console.log(people)   

猜你喜欢

转载自blog.csdn.net/qq_45549336/article/details/107908874
今日推荐