JS实现继承

45 阅读1分钟
  • 使用原型链
function Animal(legsNum) {
    this.legsNum=legsNum
}
Animal.prototype.type = '动物'

function Cat(name) {
    this.name = name
    Animal.call(this,4)
}

Cat.prototype.__proto__ = Animal.prototype
Cat.prototype.kind = '猫'
Cat.prototype.run = function () {
    console.log(`${this.name} is running`);
}
let cat1 = new Cat('猫咪')
cat1.run()
console.log(cat1.legsNum);
  • 使用class
class Animal{
    constructor(legsNum) {
        this.legsNum=legsNum
    }

}
class Cat extends Animal{
    constructor(name) {
        super(4)
        this.name=name
    }
    run() {
        console.log(`${this.name} is running`);
    }
}

let cat1 = new Cat('猫咪')
cat1.run()