1.传统的继承方式-原型链形式:缺点:过多的继承了没有用的属性 比如Father工厂里面创建的name
Father.prototype.lastName = "teng";
function Father(){
this.name = "anchao"
}
var father = new Father();
Son.prototype =father;
function Son(){
}
var son = new Son();
2.借用构造函数来继承,使用call和apply改变this指向,借用别人的工厂创建了自己的对象。缺点:不能继承别人工厂的原型 比如访问student.address = undefined;
Person.prototype.address = "地球";
function Person(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
this.sing = function(){
console.log("I am"+this.name);
}
}
function Student(name,sex,age,className){
Person.call(this,name,sex,age);
this.className = className;
}
var student = new Student("tenganchao","male",26,"三年五班");
3.共享原型来继承。缺点:不能更改儿子的原型,否则父亲的原型也跟着变化
Father2.prototype.lastName = "teng";
function Father2(){
this.name = "anchao"
}
function Son2(){
}
function inherit(Target,Origin){
Target.prototype = Origin.prototype
}
inherit(Son2,Father2);
var son2 = new Son2();
4.圣杯模式。在共享原型的基础上,通过一个function F(){} 来改掉共享原型上的缺点,这样即能达到继承效果,又可以在自己原型链上进行更改
Father3.prototype.lastName = "teng";
function Father3(){
}
function Son3(){
}
function inherit3(Target,Origin){
function F(){};
F.prototype = Origin.prototype;//将原构(父)造函数与F构造函数共享一个原型
Target.prototype = new F();//将目标(子)构造函数的原型指向了通过new F()创建的对象
Target.prototype.constuctor = Target;//将constructor复原
Target.prototype.uber = Origin.prototype;//查找继承的超类
}
inherit3(Son3,Father3);
var son3 = new Son3();
JavaScript继承模式详解
本文深入探讨JavaScript中四种经典继承方式:原型链继承、借用构造函数继承、共享原型继承及圣杯模式继承。每种方式均有其优缺点,如原型链继承易导致过度继承,借用构造函数继承无法获取原型属性,共享原型继承影响父类原型,而圣杯模式则在保留优点的同时解决了共享原型的局限性。
539

被折叠的 条评论
为什么被折叠?



