JS常见的两种继承方案

47 阅读1分钟
  1. ES6 extends继承
class Person{
    constructor(name){
        this.name = name
        this.permission = ['user','salary','vacation']
    }
    
    say(){
        console.log(`${this.name} says`)
    }
}
class Staff extends Person{
    constructor(name,age){
        super(name)
        this.age = age
    }
    eat(){
        console.log("eat")
    }
}
  1. 组合+寄生式继承
function clone(parent,child){
    child.prototype = Object.assign(parent.prototype)
    child.prototype.constructor = child
}
function Parent(){
    this.name = 'parent'
    this.play = [1,2,3]
}
Parent.prototype.getName = function(){
    return this.name
}
function Child(){
    Parent.call(this)
    this.friends = 'child5'
}
clone(Parent,Child)
Child.prototype.getFriends = function(){
    return this.friends
}