Skip to content

圣杯模式继承,企业级继承

圣杯模式继承也称为企业级的继承方式,结合了原型链继承和构造函数继承的优点,它可以让子类同时继承父类的实例属性和原型属性,确保属性和方法的正确继承

js
function Professor() {
  this.name = 'Mr.zhang';
  this.mSkill = 'JS/JQ';
}
Professor.prototype = {
  students: 300
}

function Teacher() {
  this.name = 'Mr.wang'
}

// 创建缓存层
function Buffer() {}
// 重写Bufffer.prototype
Buffer.prototype = Professor.prototype;
// 重写Teacher.prototype
Teacher.prototype = new Buffer();

var t1 = new Teacher();
console.log(t1);


// 此时原型链形式
new Teacher() {
  name:'Mr.wang'
  __proto__: new Buffer() {
    __proto__: Professor.prototype: {
      students: 300
      __proto__: Object.prototype
    }
  }
}

上面利用圣杯模式实现了继承,但是不合适日常开发。需要将圣杯模式通过函数进行封装

js
function Teacher() {}
function Student() {}

/**
 * @params {* Target: 目标对象}
 * @params {* Origin: 源始对象}
 *
 */
function inherit(Target, Origin) {
    var Buffer = function () {}
    Buffer.prototype = Origin.prototype
    Target.prototype = new Buffer()
    // 设置目标原型的constructor
    Target.prototype.constructor = Target
    // 设置继承的父类
    Target.prototype.super_class = Origin
}

// 实现圣杯继承
inherit(Student, Teacher)

闭包封装圣杯模式

js
// 利用闭包封装圣杯模式函数
function test() {
    var Buffer = function () {}
    function inherit(Target, Origin) {
        Buffer.prototype = Origin.prototype
        Target.prototype = new Buffer()
        Target.prototype.constructor = Target
        Target.prototype.super_class = Origin
    }
    return inherit
}

// 模块化封装圣杯继承
var inherit = (function () {
    var Buffer = function () {}
    return function (Target, Origin) {
        Buffer.prototype = Origin.prototype
        Target.prototype = new Buffer()
        Target.prototype.constructor = Target
        Target.prototype.super_class = Origin
    }
})()

inherit(Student, Teacher)