如何实现继承?

57 阅读1分钟

一、使用原型链

function Animal(legNumber) {
  this.legNumber = legNumber
}
Animal.prototype.kind = "动物"
function Dog (name) {
  this.name = name
  Animal.call(this,4)
}
Dog.prototype.say = function () {console.log("汪汪汪")}
Dog.prototype._proto_ = Animal.prototype
const d1 = new Dog("旺财")
console.dir(d1)

如果_proto_不管用,也可以加上这三句代码

function f (){}
f.prototype = Animal.prototype
Dog.prototype = new f()

二、使用class

class Animal {
  constructor(legNumber){
    this.legNumber = legNumber
  }
  kind = "动物"
}
class Dog extends Animal {
  constructor(name) {
    super(4)
    this.name = name
  }
  say(){console.log("h1")}
}

三、使用 object.create()