JavaScript实现继承的两种形式

34 阅读1分钟

第一种:JS使用class实现继承


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

class Dogs extends Animal{  //关键代码 extends
    constructor(name){
        super(4)   //关键代码  super
        this.name = name
    }
    say(){
        console.log(`这是${this.name},有${this.legsNumber}条腿`)
    }
}

const dog1 = new Dogs('哮天犬')
dog1.say()

第二种:JS用原型链实现继承


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

function Dog(name){
    this.name = name
    Animal.call(this,4) //关键代码1
}

Dog.prototype.__proto__ = Animal.prototype //关键代码2,这句如果被ban,看下面的三行

Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
    console.log(`这是${this.name},有${this.legsNumber}条腿`)
}

const dog2 = new Dog('哮天犬')
dog2.say()


如果上面关键代码2被禁,可以用下面三行代替

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

三:总结

一般都是用class实现继承,理由是简单容易理解