1)核心: 将父类实例作为子类原型
2)优点: 方法复用
3)缺点:
1、创建子类实例的时候,不能传参
2、子类实例共享了父类的构造函数的引用属性,比如foods
3、无法实现多继承
//父类
function School(name,foods){
this.name=name
this.foods=['甜品']
this.person=function(){
console.log(this.name+'吃'+this.foods);
}
}
//父类原型对象添加方法
School.prototype.print=function(){
console.log(this.name,this.foods);
}
//子类
function Student(){
}
//原型继承
Student.prototype=new School()
//纠正constructor指向
Student.prototype.constructor=Student
//创建实例
let stu1=new Student()
let stu2=new Student()
stu1.name='jack'
stu1.foods.push('罐头')
console.log(stu1.name);
console.log(stu1.foods);
stu1.person()
stu1.print()
console.log('——————————————————————————————————————————————');
stu2.name='rose'
stu2.foods.push('香蕉')
console.log(stu2.name);
console.log(stu2.foods);
stu2.person()
stu2.print()
1)核心: 借用父类的构造函数来增强子类实例,等于复制父类的实例属性给子类
2)优点: 实例之间独立
1、创建子类实例,可以向父类构造函数传参数。
2、子类实例不共享父类的构造函数的引用属性。如foods属性
3、可实现多继承(通过多个call或者apply继承多个父类)
3)缺点
1、父类的方法不能复用
由于方法再父构造函数中定义,导致方法不能复用(因为每次创建子类实例都要创建一遍方法)
2、子类实例,继承不了父类原型上的属性(因为没有用到原型)
function School(name,foods){
this.nam