JS 如何实现类 和 继承

75 阅读1分钟

实现类

  • 方法 1 :使用原型
function Dog(name){
  this.name = name
  this.legsNumber = 4
}
Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
  console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
const dog1 = new Dog('哈士奇') // Dog 函数就是一个类
dog1.say()
  • 方法 2 :使用 class
class Dog{
  kind = '狗' // 等价于在 constructor 里写 this.kind = '狗'
  constructor(name){
    this.name = name
    this.legsNumber = 4
  }
  say(){
    console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
  }
}
const dog1 = new Dog('哈士奇')
dog1.say()

实现继承

  • 方法 1:使用原型链
function Animal(legsNumber){
  this.legsName = legsName
}
Animal.proptype.kind = '动物'

function Dog(name){
  this.name = name
  Animal.call(this,4) // 关键 1
}
Dog.prototype.__proto__ = Animal.prototype // 关键 2
Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
 console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
const dog1 = new Dog('哈士奇') // do1 就继承了 Animal 的属性
  • 方法 2:使用 class
class Animal {
  constructor(legsNumber){
   this.legsNumber = legsNumber
  }
  run(){}
}
class Dog extends Animal {
  constructor(name){
    super(4)
    this.name = name
  }
  say(){
     console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
  }
}