继承模式发展史 传统形势、借用构造函数、共享原型、圣杯模式

版权声明:版权声明:@BU-KX-Z 本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41539580/article/details/82531927

继承模式发展史

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

    过多的继承了没用的属性
    
  2. 借用构造函数

    不能继承借用构造函数的原型
    每次构造函数都要多走一个函数
    
  3. 共享原型

    不能随便的更改在自己的原型
    
  4. 圣杯模式

原型链:

Grand.prototype.lastName = "你";
function Grand() {};
var grand = new Grand();
Father.prototype = grand;
function Father() {
    this.name = "Woo";
}
var father = new Father();
Son.prototype = father;
function Son() {}
var son = Son();

结果如下:
BU
从头继承到尾,想要的继承了,不想要的也继承了,造成了用法和效率的不好。所以衍生出了下面的放法 ☟


借用构造函数:

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)
    this.grade = grade
}
var student = new Student("你", 12, "女", 3);

运行结果:
这里写图片描述

视觉上的优化,每次都要调用一次函数。
借用的构造函数全部包含要用的属性,建议用借用构造函数

共享原型:

Father.prototype.lastName = "BU";
function Father() {
}
function Son() {
}
function inherit(Target, Origin) {
    Target.prototype = Origin.prototype;
}
inherit(Son, Father)
Son.prototype.sex = 'male';
var son = new Son();
var father = new Father();
构造函数共用一个原型
导致改变自己的原型另一个也改变

执行如下
这里写图片描述


圣杯模式:

function inherit(Target, Origin) {
    function F() {}
    F.prototype = Origin.prototype;
    Target.prototype = new F();
    Target.prototype.constuctor = Target; //把Target的构造函数指向归位
    Target.prototype.uber = Origin.prototype; //为了让我们知道Target真正继承自谁
}

代码案例实现:

function inherit(Target, Origin) {
    function F() {}
    F.prototype = Origin.prototype;
    Target.prototype = new F();
    Target.prototype.constuctor = Target;
    Target.prototype.uber = Origin.prototype;
}
Father.protoptype.lastName = "BuKaiXiu";
function Father() {};
function Son() {};
inherit(son,Father);
Son.prototype.sex = 'male';
var son = new Son();
var father = new Father();

结果:
Bu

猜你喜欢

转载自blog.csdn.net/weixin_41539580/article/details/82531927