Skip to main content

手写继承

class

class Animal{
constructor(legsNumber){
this.legsNumber = legsNumber
}
run (){}
}

class Dog extends Animal {
constructor(name){
super(4) // 继承Animal自身属性 并向Animal传参 this.legsNumber =
this.name = name
}
say(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
// 自动继承Animal共有属性 ,可以从原型链进行获取
}

使用原型

  1. 私有属性继承:在子函数内调用父函数
  2. 共有属性: Dog.prototype._proto_ = Animation.prototype
const Animal = function (legsNumber) {
this.legsNumber = legsNumber
}

const Dog = function (name) {
this.name = name
// 继承Animal自身属性 并向Animal传参 this.legsNumber = 4= 4
Animal.call(this,4)
}

Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
// 继承Animal共有属性
Dog.prototype.__proto__ = Animal.prototype

使用方法:

const d1 = new Dog('啸天') // Dog 函数就是一个类
console.log(d1)