一、继承基础
继承:继承是和构造函数相关的一个应用;是指让一个构造函数去继承另一个构造函数的属性和方法。所以继承一定是出现在两个构造函数之间的。
继承的作用:
1.可以减少代码重复出现的现象,使代码结构更简洁
2.如果两个构造函数要实现相同的功能,使用继承就更简单方便
二、常见的继承方式
1、原型继承
原型继承,是在本身的原型链上再加一层关系;将继承者的原型对象与被继承者的实例化对象关联起来。
function Father(name,age){
this.name = name
this.age = age
}
Father.prototype.say=function(){
console.log('say say say ');
}
function Son(name,age){
}
//可以增加新的方法,但是父级构造函数不能使用子级构造函数的方法
Son.prototype.like=function(){
console.log('love lee');
}
// 将son构造函数的原型对象与father构造函数的实例化对象连接起来
Son.prototype = new Father()
let s = new Son('mino',18)
//可以继承到say方法
s.say()
这样Son()函数就能够使用Father()函数的方法,也能继承到它的属性。
但是继承来的属性并不在子类实例的身上,而是在其原型对象上。另外,一个构造函数的内容,可以在两个位置传递参数。
// 可以在这里传递参数
Son.prototype = new Father('mino',18)
//也可以在这里传递参数
let s = new Son('mino',18)
s.say()
原型继承的优点:构造函数体内的内容和原型对象上的内容都可以继承
缺点:一个构造函数的内容,在两个地方传递参数
继承来的属性不在子类实例对象的身上
2.借用构造函数继承
即把父类构造函数拿来借用一下,利用call方法,改变其this指向
function Father(name,age){
this.name = name
this.age = age
}
Father.prototype.say=function(){
console.log('say say say ');
}
// 改变father构造函数的this指向,但是不能继承父级构造函数原型对象上的方法
function Son(name,age){
//这里将this指向改为了子级构造函数的this,即子级构造函数的实例化对象
Father.call(this,name,age)
}
let s = new Son('mino',18)
console.log(s.name);
通过改变父级构造函数的this指向,使this指向子级构造函数的实例化对象,这父级所实例的内容就可以传入到子级构造函数的实例对象上。但这种方式只能继承父级构造函数体内的内容,不能继承原型对象上的内容。
优点:继承来的属性是在自己身上的
缺点:
只能继承父类构造函数体内的内容
父类原型上的内容不能继承
3.组合继承
即将前面两种方法结合起来使用
function Father(name,age){
this.name = name
this.age = age
}
Father.prototype.say=function(){
console.log('say say say ');
}
// 改变father构造函数的this指向,但是不能继承父级构造函数原型对象上的方法
function Son(name,age){
Father.call(this,name,age)
}
Son.prototype=new Father()
let s = new Son('mino',19)
s.say()
console.log(s.name);
优点:
1.父类构造函数体内和原型上的内容都能继承
2.继承下来的属性放在自己身上
3.在一个位置传递所有的参数
缺点:
当你给子类添加方法的时候,实际上是添加在父类的实例身上 ,因为子类的原型对象指向的是父类的实例化对象。
4.ES6的继承
其实是对组合继承的一种封装
class Father{
constructor(name,age){
this.name = name
this.age = age
}
say(){
console.log('say say say ');
}
}
class Son extends Father{
constructor(name,age){
//利用super实现继承
super(name,age)
}
}
let s =new Son('mino',19)
s.say()
console.log(s.name);
注意:super()必须写在最前面