目录
1.原型链继承
固定格式:
子函数.prototype=new 父函数();
原理:通过改变一个函数的原型指向来完成的继承
优点:暂无(2021.2.18)
缺点:
- 因为所有子函数的实例都共用同一个父类实例,所以如果一处子函数实例对象修改父函数属性的值,那么其他子函数实例的内容也通过会被修改
- 创建子类型函数实例时,不能像父函数传递参数
示例代码:
//Humans是父函数,Mans是子函数
function Humans(){
this.foot=2;
}
Humans.prototype.getFoot=function(){
alert(this.foot);
}
function Mans(){
this.head=3;
}
Mans.prototype=new Humans(); //Mans继承Humans
Mans.prototype.getHead=function(){ //注意向子类原型中添加属性或方法要写在继承语句之后
alert(this.head);
}
var man1=new Mans();
man1.getFoot();
man1.getHead();
2.借用构造函数继承(继承属性)
在子函数内部使用apply或者call完成构造函数继承
固定格式:
//语法卸载子函数函数体内
//使用apply
父函数.apply(this);
//使用call
父函数.call(this);
原理:此继承相当于把父函数函数体内的属性或方法拷贝了一份副本给子函数的实例使用
优点:子函数实例不共用同一个父函数的属性或方法,修改一处不会导致全局被修改,可以向父函数传参(2021.2.18)
缺点:只能继承父函数函数体内的属性或方法,无法继承原型中的任何东西
示例代码:
//Humans是父函数,Mans是子函数
function Humans(){
this.foot=2;
}
Humans.prototype.getFoot=function(){
alert(this.foot);
}
function Mans(){
this.head=3;
Humans.call(this);
}
Mans.prototype.getHead=function(){ //注意向子类原型中添加属性或方法要写在继承语句之后
alert(this.head);
}
var man1=new Mans();
alert(man1.foot);
alert(man1.head);
3.组合继承
使用原型链继承和借用构造函数继承实现组合继承
固定格式:
//语法写在子函数函数体内
//使用apply
父函数.apply(this);
//使用call
父函数.call(this);
//原型链继承
子函数.prototype=new 父函数();
原理:借用构造函数继承父函数函数体内的东西,原型链继承父函数原型中的东西(弥补了结构构造函数的缺点)
优点:子函数实例不共用同一个父函数的属性或方法,修改一处不会导致全局被修改,可以向父函数传参,同时子函数又继承父函数的原型(2021.2.18)
缺点:暂无
示例代码:
//Humans是父函数,Mans是子函数
function Humans(){
this.foot=2;
}
Humans.prototype.getFoot=function(){
alert(this.foot);
}
function Mans(){
this.head=3;
Humans.call(this); //继承属性
}
Mans.prototype=new Humans(); //继承原型
Mans.prototype.getHead=function(){ //注意向子类原型中添加属性或方法要写在继承语句之后
alert(this.head);
}
var man1=new Mans();
alert(man1.foot);
alert(man1.head);
man1.getFoot();
4.使用call向父函数中传参
固定格式:
//参数传递的顺序和父函数()中参数的顺序一致
父函数.call(this,参数1,参数2....)
示例代码:
//Humans是父函数,Mans是子函数
function Humans(foot){ //注意,此时()里的foot和函数体内的foot不是一个foot
this.foot=foot; //this.foot=参数foot
}
Humans.prototype.getFoot=function(){
alert(this.foot);
}
function Mans(){
this.head=3;
Humans.call(this,2); //继承属性
}
Mans.prototype=new Humans(); //继承原型
Mans.prototype.getHead=function(){ //注意向子类原型中添加属性或方法要写在继承语句之后
alert(this.head);
}
var man1=new Mans();
alert(man1.foot);
alert(man1.head);
man1.getFoot();
声明:所有内容均为个人理解总结,如理解有误请及时纠正我的错误,以免误人子弟,谢谢!!!