JS如何实现类和继承?

107 阅读1分钟

使用原型

function Cat(name){
    this.name = name
    this.legsNumber = 4
}
Cat.prototype.kind = '猫'
Cat.prototype.say = function(){
    console.log(`喵喵喵' 我是${this.name},我有${this.legsNumber}条腿。`)
}
Cat.prototype.run = function(){
    console.log(`${this.legsNumber}条退跑起来。`)
}
const c = new Cat('布偶')  // Cat函数就是一个类
c.say()

使用class

class Cat {
    kind = '猫'  // 等价于在 constructor 里写 this.kind = '猫'
    constructor(name){
        this.name = name
        this.legsNumber = 4
    }
    say(){
        console.log(`喵喵喵' 我是${this.name},我有${this.legsNumber}条腿。`)
    }
    run(){
        console.log(`${this.legsNumber}条退跑起来。`)
    }
}
const c = new Cat('布偶')
c.say()

继承

使用原型链

function Animal(legsNumber){
    this.legsNumber = legsNumber
}
Animal.prototype.kind = '动物'

function Cat(name){
    Animal.call(this, 4) // this.legsNumber = 4
    this.name = name
}
Cat.prototype.__proto__ = Animal.prototype  // 关键代码,但这句代码被禁用了。
Cat.prototype.say = function(){
    console.log(`喵喵喵' 我是${this.name},我有${this.legsNumber}条腿。`)
}
const c = new Cat('布偶')  // Cat函数就是一个类
c.say()

如何替换被ban掉的代码

我们直接写Cat.prototype = Animal.prototype,会把this.legsNumber = legsNumber也加到Cat上。所以我们可以使用下面的代码。
先声明一个空的函数f,然后让这个函数的prototype指向Animal.prototype,这样这个空函数就没有Aminal的函数体,只有 Animal.prototype了。然后我们使用new ,将Cat.prototype指向f.prototype即可。

var f = function(){ }
f.prototype = Animal.prototype
Cat.prototype = new f()

使用class

class Animal{
  constructor(legsNumber){
    this.legsNumber = legsNumber
  }
  run(){}
}
class Cat extends Animal{
  constructor(name) {
    super(4)
    this.name = name
  }
  say(){
    console.log(`喵喵喵' 我是${this.name},我有${this.legsNumber}条腿。`)
  }
}