JavaScript 继承 圣杯模式

  • 发展史

        1.传统形式  -->  原型链

                过多的继承了没用的属性

         2.借用构造函数

                 不能继承借用构造函数的原型

                 每次构造函数都要走一个函数

          3.共享原型

                 不能随便改动自己的原型

          4.圣杯模式

// 1. 继承了所有信息
Grand.prototype.lastName = 'zhang';
function Grand() {}

var grand = new Grand();

Father.prototype = grand;
function Father() {
    this.name = 'san';
}

var father = new Father();

Son.prototype = father;
function Son = new Son();

// 2. 借用构造函数 每次都要用new
function Person(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

function Student(name, age, sex, grade) {
    Person.call(this, name, age, sex);
    this.grade = grade;
}

var student = new Student('xiaoming', 19, 'male', 2018);

// 3. 共用原型
Father.prototypoe.lastName = 'zhang';

function Father() {}

function Son() {}

function inherit(Target, Origin) {
    Target.prototype = Origin.prototype;
}
inherit(Son, Father); // Son.prototype = Father.prototype
var son = new Son();
console.log(son.lastName); // 'zhang'

Son.prototype.sex = 'male';
console.log(son.sex); // 'male'

var father = new Father();
console.log(father.sex); // 'male' 

// 4. 圣杯模式
function inherit(Target, Origin) {
    function F() {};
    F.prototype = Origin.prototype;
    Target.prototype = new F();
    Target.prototype.constuctor = Target; 
    Target.prototype.uber = Origin.prototype; // 超级父级
}

// 4.1 圣杯模式
var inherit = (function(){
    var F = function(){}; // 私有化变量 外部无法访问
    return function (Target, Origin) {
        F.prototype = Origin.prototype;
        Target.prototype = new F();
        Target.prototype.constuctor = Target;
        Target.prototype.uber = Origin.prototype;
    }
}())

猜你喜欢

转载自blog.csdn.net/fanlixing6/article/details/85088347