创建一个人类然后继承学生类
1.原型继承:People继承Student,将Student对象赋值在People的原型上,代码举例如下:
function Student(name,age){
this.name=name
this.age=age
}
Student.prototype.task=function(){
console.log(this.name+"的主要任务是上学")
}
function People(name,age){
//构造函数里无内容,传入的参数无效
}
People.prototype=new Student("tom",21)
var p1=new People("marry",21);
var p2=new People("jerry",22);
console.log(p1.name,p2.name);
上段代码的输出结果都是tom,说明了无法改变People.prototype=new Student("tom",21)这句代码的入参
2.冒充继承:通过call或apply来更改对应的this指向达到继承目的
function Student(name,age){
this.name=name
this.age=age
}
Student.prototype.task=function(){
console.log(this.name+"的主要任务是上学")
}
function People(name,age){
Student.call(this,name,age);
}
var p=new People("marry",21);
console.log(p.name);
p.task();
运行代码,控制台输出结果为:
说明冒充继承无法继承父类的原型中的方法
3.混合继承:原型继承+冒充继承
function Student(name,age){
this.name=name
this.age=age
}
Student.prototype.task=function(){
console.log(this.name+"的主要任务是上学")
}
function People(name,age){
Student.call(this,name,age);//通过call或apply来更改对应的this指向new出来的实例对象p
}
People.prototype=new Student();//将Student的原型继承过来,可继承原型中的方法
var p=new People("marry",21);
console.log(p.name);
p.task();
控制台输出的结果为:
通过这种方式,子类能完全继承父类的构造函数以及原型上的方法