JavaScript如何实现继承(原型链和class)

85 阅读1分钟

方式一:使用原型链

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

function Dog(){
    this.name = name
    Animal.call(this,4) //关键代码1
}
//Dog.prototype.__proto__ = Animal.prototype //这句话被ban了怎么办 看下面👇
let f = function(){}
f.prototype = Animal.prototype
Dog.prototype = new f()
//new做五件事情
/*
    1. 创建临时对象
    2. this = 临时对象
    3. this.__proto__ = 构造函数的prototype
    4. 执行构造函数
    5. 返回this
 而我们这里需要的就是第三步
 那为什么不直接用:
 Dog.prototype = new Animal()
 因为不想要Animal上的this.legsNumber,把Animal的constructor架空,不执行,即放弃第四步。
*/
Dog.prototype.kind = '狗'  
Dog.prototype.say = function(){  
    console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)  
}
const d1 = new Dog('啸天') 

方式二:使用class

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