6

31 阅读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)
//    }
//}
基于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)
    }
}