为什么继承?提高代码的复用性。
1.原型链继承
function Parent(name,age){
this.name=name
this.age=age
}
Parent.prototype.eat=function(){
console.log("....")
}
function Child(name){
this.name=name
this.age=age
}
Child.prototype=new Parent()//原型链继承,改变Child的原型对象
let c=new Child('zs',18)
c.eat()//继承了父类原型对象上的属性和方法,子类可以调用
2.组合继承(原型链+call)
function Parent(name,age){
this.name=name
this.age=age
console.log('parent执行了')
}
Parent.prototype.eat=function(){
console.log("....")
}
function Child(name,age){
Person.call(this,name,age)//继承Person的私有属性,改变this,并执行
}
Child.prototype=new Parent()//原型链继承,改变Child的原型对象
//Child.prototype=Object.create(Person.prototype)//改变Child的原型对象指向Person的原型对象,与new作用一样,当相比new没有执行父类的代码
let c=new Child('zs',18)
c.eat()//继承了父类原型对象上的属性和方法,子类可以调用
3.es6
class Person{
//new时自动执行
constructor(name,age){
//私有属性
this.name=name
this.age=age
}
//放入原型链上,公有属性
eat(){
console.log('111')
}
}
class Child extends Parent{
constructor(name,age){
super(name,age)
}
}