JS继承方式

120 阅读1分钟

寄生组合式继承

  • 实例的属性私有、prototype公用(个人理解)
  • 只调用了一次父类,也避免了在子类的prototype创建不必要的属性,同时原型链还保持不变 这是最成熟的方式
function Person(name, age) {
    this.name = name
    this.age = age
}

Person.prototype.sayName = function () {
    console.log(this.name, this.age)
}

function ChinaPerson(features, name, age) {
    Person.call(this, name, age)
    this.features = ['中国', ...features]
}

ChinaPerson.prototype = Object.create(Person.prototype)
ChinaPerson.constructor = ChinaPerson

ChinaPerson.prototype.sayFeatures = function () {
    console.log(this.name, this.features)
}

const zhangsan = new ChinaPerson(['170cm', '高'], '张三', 28)
zhangsan.sayFeatures()
zhangsan.sayName()

const lisi = new ChinaPerson(['160cm', '矮', '矬', '穷'], '李四', 35)
lisi.sayFeatures()
lisi.sayName()

ES6 class继承

class Person {
    constructor(name, age) {
        this.name = name
        this.age = age
    }

    sayName() {
        console.log(this.name, this.age)
    }
}

class ChinaPerson extends Person {
    constructor(features, ...arg) {
        super(...arg);
        this.features = ['中国', ...features]
    }

    sayFeatures() {
        console.log(this.name, this.features)
    }
}

const zhangsan = new ChinaPerson(['170cm', '高'], '张三', 28)
zhangsan.sayFeatures()
zhangsan.sayName()

const lisi = new ChinaPerson(['160cm', '矮', '矬', '穷'], '李四', 35)
lisi.sayFeatures()
lisi.sayName()