js的继承

发布时间 2023-04-05 19:07:54作者: 爱吃蔬菜的小红帽

ES6 的继承:子 extends 父,哪里继承哪里写一个super()

代码:

class Parent{

constructor(){
     this.age=18
}
}

class Child extends Parent{     //子继承父

constructor(){
     super()            //加上super(),要不然会报错
     this.age=18
}
}
let o = new Child()
 
原型链的继承:new一个父的函数赋值给子函数的原型
代码:
function Parent(){
this.age=20
}
function Child(){
this.name="王五"
}
Child.prototype=new Parent()    //给子的原型上new
let o = new Child()        
 
借用构造函数的形式:(改变this指向)
代码:
function Parent(){
this.age=20
}
function Child(){
this.name="王五"
Parent.call(this)
}
let o = new Child()
 
组合式继承:就是结合构造函数继承和原型链继承实现的
function Parent(){
this.age=20
}
function Child(){
this.name="王五"
Parent.call(this)
}
Child.prototype=new Parent()
let o = new Child()