JS继承
继承:JS中的继承分为原型链继承、组合式继承、寄生组合式继承、借用构造函数继承、ES6中class以及继承
1、原型链继承
原型链继承:让子类的原型指向父类的实例
特点:
1、JS继承不像其他语言中的继承一样,js中它是把父类的实例放到子类的原型链上,子类实例想要去调用这些属性和方法的时候,实际上是基于__proto__原型链查找的形式去完成的
2、子类实例可以直接修改父类上的方法。
3、父类中私有的属性和方法,在实现原型链继承之后,都会变成子类公有的属性和方法
//代码展示
//父类构造函数
function Parent(x){
this.x=x
}
//父类原型
Parent.prototype.getX=function(){
console.log("getX",this.x)
}
let P1=new Parent(100)
//子类
//子类构造函数
function Child(y){
this.y=y
}
Child.prototype=new Parent(100)
//constructor 用来获取对象的构造函数
Child.prototype.constructor=Child
Child.prototype.getY=function(){
console.log("getY",this.y);
}
//子类实例
let C1=new Child(200)
图片展示
2、组合式继承
组合式继承:结合原型链继承和借用构造函数继承的方法
特点:
1、子类实例可以使用父类的私有属性和方法
2、父类私有的属性和方法会变成子类实例的私有属性和方法
3、子类实例父类公有的属性和方法
4、子类的原型链上会存在一分多余的父类私有属性
//父类构造函数
function Parent(x){
this.x=x
this.say=function(){
console.log('QQ')
}
}
//父类原型
Parent.prototype.getX=function(){
console.log("getX",this.x)
}
let P1=new Parent(100)
//子类
//子类构造函数
function Child(y,x){
Parent.call(this,999)
this.y=y
}
Child.prototype=new Parent(100)
Child.prototype.constructor=Child
Child.prototype.getY=function(){
console.log("getY",this.y);
}
//子类实例
let C1=new Child(100)
3、寄生组合式继承
寄生组合式继承:结合原型链继承和借用构造函数继承的方法,同时需要自己创建prototype,实现寄生组合式继承
特点:
1、最完美的JS继承解决方案
2、父类私有的属性和方法,成为子类实例私有的属性和方法
3、父类公有的属性和方法,成为子类实例公有的属性和方法
4、子类实例修改公有的属性和方法不会影响到父类的实例
//父类构造函数
function Parent(x){
this.x=x
this.say=function(){
console.log('QQ')
}
}
//父类原型
Parent.prototype.getX=function(){
console.log("getX",this.x)
}
let P1=new Parent(100)
//子类
//子类构造函数
function Child(y,x){
Parent.call(this,999)
this.y=y
}
//Child.prototype=new Parent(100)
Child.prototype=Object.create(Parent.prototype)
Child.prototype.constructor=Child
Child.prototype.getY=function(){
console.log("getY",this.y);
}
//子类实例
let C1=new Child(100)
//Object.create(obj) 创建一个空的对象,并且让这个空对象__proto__指向传递的第一个参数
Object.create=function(obj){
function NewObj(){}
NewObj.prototype=obj
return new NewObj()
}
图片展示
4、借用构造函数继承
借用构造函数继承:在子类内,使用call()调用父类方法,并将父类的this修改为子类的this,相当于把父类的实例属性复制了一份放到子类的函数内
或
在Child方法中把Parent当作普通的函数执行,让Parent中的this指向Child的实例, 相当于给Child的实例设置了私有的属性和方法
特点:
1、只能继承父类的私有属性和方法(因为只是把Parent当做普通函数执行一次,跟Parent的原型上的属性和方法没有任何关系)
2、父类私有的属性和方法都会变成子类的私有属性和方法
//父类构造函数
function Parent(x){
this.x=x
this.say=function(){
console.log('QQ')
}
}
//父类原型
Parent.prototype.getX=function(){
console.log("getX",this.x)
}
//子类
//子类构造函数
function Child(y,x){
Parent.call(this,x)
this.y=y
}
Child.prototype.getY=function(){
console.log("getY",this.y);
}
//子类实例
let C1=new Child(200,100)
5、ES6中class以及继承
ES6中class以及继承:通过extends来实现的继承,这比通过ES5修改原型链实现继承,要清晰和方便很多。
特点:
1、父类的稀有属性和方法,会变成子类的私有属性和方法
class Parent(){
constructor(x){
this.x=x
}
}
ParentX(){
console.log(this.x)
}
class Child extends Parent{
constructor(y){
super(999)
this.y=y
}
ChildY(){
console.log(this.y)
}
}
let C=new Child(500)