如何理解 JS 的继承?

98 阅读1分钟

1.基于原型的继承

function Parent(name1){
  this.name1 = name1
}
Parent.prototype.pMethod = function(){
  console.log(this.name1)
}

function Child(name2, name1){
    Parent.call(this, name1) // 得分点
    this.name2 = name2
}
Child.prototype.__proto__ = Parent.prototype 
//上面这句代码的古板写法应该是下面三句
//const empty = function(){}
//empty.prototype = Parent.prototype
//Child.prototype = new empty()
//古板写法额外加分

Child.prototype.cMethod = function(){
    console.log(this.name2)
}

//如果写成下面这种,就扣分
//Child.prototype = {
//    cMethod: function(){
//        console.log(this.name2)
//    }
//}

2.基于 class 的继承

class Parent{
    constructor(name1){
        this.name1 = name1
    }
    pMethod(){
        console.log(this.name1)
    }
}
class Child extends Parent{
    constructor(name2, name1){
        super(name1) // 得分点
        this.name2 = name2
    }
    cMethod(){
        console.log(this.name2)
    }
}