我们知道在es6中我们使用extend实现继承,当然在我们也可以使用js实现面向对象的继承
传统方式--原型链
Grand.prototype.lastName="shu";
function Grand(){
}
var grand =new Grand();
Father.prototype=grand;
function Father(){
}
var father=new Father();
console.log(father.lastName);
//shu
通过使用原型链可以实现继承,但是它过多的继承了没有用的属性,很快就离开了继承的舞台。
借用构造函数
function Father(lastName,age,sex) {
this.lastName='shu';
this.sex='male';
this.age=38
}
function Son(lastName,sex,age) {
Father.call(this,lastName,sex);
this.age=18
}
var son =new Son();
console.log(son);
// {
// age:18
// lastName:"shu"
// sex:"male"
// }
解决了上面的缺点,但是出现了新的问题,只能继承构造函数,并不能继承构造函数的原型,且每次都需要调用浪费性能
共享原型
Grand.prototype.lastName="shu";
function Grand(){
}
function Father(){
}
Father.prototype=Grand.prototype
var father =new Father();
console.log(father.lastName);
//shu
令Father的原型地址指向Grand的原型地址,可以较好的实现继承,下面我们可以封装一个方法实现这种继承
function inherit(Target,Origin){
Target.prototype=Origin.prototype;
}
但是后续在Father上添加原型方法或属性时候,Grand也会有这个方法或属性。
圣杯模式
Father.prototype.lastName="shu";
function Father(){
}
function Son(){
}
function F(){
}
F.prototype=Father.prototype;
Son.prototype=new F();
var son =new Son();
console.log(son.lastName);
//shu
我们可以通过一个中间函数,使用原型链的方法完成这个继承的交接,接下来我们就可以在Son上添加属性方法,而不会在影响Father了。我们继续来封装这个方法
function inherit(Target,Origin){
function F(){}
F.prototype=Origin.prototype;
Target.prototype=new F();
Target.prototype.constuctor=Target;
Target.prototype.uber = Origin.prototype //保存了它的超类(也就是它真正继承的对象)
}
这个继承模式是现在比较完善的。