最常见的三种继承方式:
1.构造函数继承
//构造函数继承
function People(name){
//实例属性
this.name = name
}
function Student(school){
//实例属性
this.school = school;
People.call(this,'小明') //构造函数继承
}
//实例方法
People.prototype.show = function(){
console.log('success show')
}
var stu = new Student('星星幼儿园')
stu.name; //小明
stu.show() //报错
缺点:只能继承父类的实例属性和方法,不能继承原型属性和方法
2.原型继承
//原型继承
function People(name){
//实例属性
this.name = name
}
function Student(school){
//实例属性
this.school = school
}
//实例方法
People.prototype.show = function(){
console.log('success show')
}
Student.prototype = new People() //原型继承
var stu = new Student('星星幼儿园') //创建子类实例时,无法向父类构造函数传参,因此name为undefined
stu.name; //undefined
stu.show() //success show
缺点:创建子类实例时,无法向父类构造函数传参
3.组合继承(构造函数继承 和 原型继承)
//组合继承
function People(name){
//实例属性
this.name = name
}
function Student(school){
//实例属性
this.school = school;
People.call(this,'小明')
}
//实例方法
People.prototype.show = function(){
console.log('success show')
}
Student.prototype = new People()
var stu = new Student('星星幼儿园')
stu.name; //小明
stu.show() //success show