先介绍一下什么是继承
1、继承是与 构造函数 相关的应用
2、是指让一个构造函数去继承另一个构造函数的属性和方法
3、继承是发生在两个构造函数之间
下面分别从es5和es6提供的方法介绍一下继承的常用方法
es5继承常见方法
1、原型继承
原型继承1 - 原型对象继承:
简单,方便,易操作
但是,只能继承原型身上的方法和属性,不能继承构造函数内的方法和属性
//父构造函数
function Parent(){
this.name = "parent";
}
Parent.prototype.name = "parent";
Parent.prototype.show = function(){
console.log("哈哈哈");
}
//子构造函数
function Child(){
}
// 深拷贝
for(var i in Parent.prototype){
Child.prototype[i] = Parent.prototype[i];
}
var p = new Parent();
p.show();
console.log(p.name);
var c = new Child();
c.show();
console.log(c.name);
原型继承2 - 原型链继承:
1.更加的简单,方便,易操作
2.不仅可以继承原型身上的方法和属性,而且还可以继承构造函数中的方法和属性
3.但是,不方便传参
原理:// Child的实例c —> proto —> Child.prototype —> Parent的实例 —> proto —> Parent.prototype
//父构造函数
function Parent(n)
this.name = n;
}
Parent.prototype.show = function(){
console.log(this.name);
}
//子构造函数
function Child(){
}
Child.prototype = new Parent();
var p = new Parent("张三");
console.log(p)
p.show();
console.log(p.name);
var c = new Child();
console.log(c);
c.show();
console.log(c.name);
2、借用构造函数继承 构造函数多继承
构造函数继承(改变this指向继承):
1.方便的传参
2.还可以实现多继承
3.但是,只能继承构造函数内部的属性或方法,不能继承原型身上的属性或方法
function Mp3(){
this.music = "放音乐";
}
function Camera(){
this.photo = "拍照";
}
function Tel(){
this.call = "打电话";
}
function Email(){
this.message = "发信息";
}
function MobilePhone(n){
Mp3.call(this);
Camera.call(this);
Tel.call(this);
Email.call(this);
this.name = n;
this.game = "打游戏";
}
var mp = new MobilePhone("HUAWEI P30");
console.log(mp);
3、组合继承
混合继承:构造函数继承 + 原型继承
1.略复杂
2.既可以继承构造函数,又可以继承原型
3.方便传参
4.可以多继承构造函数
5.注意:原型链继承时,依然有参数隐患
function Parent(s){
this.skill = s;
}
Parent.prototype.show = function(){
console.log(this.skill);
}
function Child(s){
Parent.call(this, s);
}
for(var i in Parent.prototype){
Child.prototype[i] = Parent.prototype[i];
}
Child.prototype.show = function(){
console.log("hello 鉴定师");
}
var p = new Parent("大鉴定师");
p.show();
var c = new Child("实习鉴定师");
c.show();
4、es6class继承
ES6的class继承,原理就是:构造函数方式继承 + 原型链继承
class Parent{
constructor(s){
this.skill = s;
}
show(){
console.log(this.skill);
}
}
//子构造函数继承父构造函数
class Child extends Parent{
constructor(s){
super(s);
}
}
var p = new Parent("大鉴定师");
p.show();
console.log(p);
var c = new Child("实习鉴定师");
c.show();
console.log(c);