JS的继承

132 阅读1分钟

1.基于原型链的继承

function Parent (){
    this.name = 'jason'
}
function Child (){
}
Child.prototype = new Parent()
let child1 = new Child()
console.log(child1.name)  //jason
child1.__proto__ === Child.prototype    //true
child1.__proto__.__proto__ === Parent.prototype    //true
child1 instanceof Child    //true
child1 instanceof Parent    //true

2.基于class继承

class Child extends Parent{
    constructor(name,age) {
        super(name);
        this.age = age
    }
    hello1(){
        console.log('My name is'+this.name+this.age+" years old")
    }
}

const dahao = new Child('dahao ',24)
dahao.hello1()