JavaScript圣杯模式继承&组合继承

2,532 阅读1分钟

圣杯模式

原理:通过小原型链,Son里加东西不会再影响Father的proto


Father.prototype

       function F(){} //中间层

       F.prototype = Father.protype

       Son.protype = new F();//依然能继承Father.prototype

写一个继承

function inherit(Target,Origin){

function F(){};

F.prototype = Origin.prototype;
Target.prototype = new F();  //两者位置不能颠倒,否则new时指向原来的原型
Target.prototype.constructor = target; //constructor归位
}

Father.prototype.lastName="Su";

function Father(){}
function Son(){}

inherit(Son,Father);
var son = newSon();
var father = newFather();

组合模式

组合继承指的是将原型链和借用构造函数的技术组合到一块,从而发挥二者之长的一种继承模式。这种方法的主要思路是使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。这样既通过在原型上定义方法实现了函数复用,又能够保证每个实例都有它自己的属性。

如下面的例子所示:

function Father(name){
    this.name = name;
    this.colors = ["red","blue","green"];
}
Father.prototype.sayName = function(){
    console.log(this.name);
}

function Son(name,age){

    Father.call(this,name);
    this.age = age;
}

//继承方法
Son.prototype = new Father();
Son.prototype.constructor = Son;
Son.prototype.sayAge = function(){
    console.log(this.age);
}

var instance1 = new Son("sugar",9);
instance1.colors.push("black");
console.log(instance1.colors);//"red,blue,green,black"
instance1.sayName();//"sugar"
instance1.sayAge();//9

优点:组合继承避免了原型链和借用构造函数的缺陷,融合了它们的优点,成为 JavaScript 中最常用的继承模式。而且,instanceof 和 isPropertyOf() 也能够用于识别基于组合继承创建的对象。

缺点:调用了两次超类的构造函数,导致基类的原型对象中增添了不必要的超类的实例对象中的所有属性。