Javascript几种继承方式
1.使用对象冒充实现继承(该种实现方式可以实现多继承)
实现原理:让父类的构造函数成为子类的方法,然后调用该子类的方法,通过this关键字给所有的属性和方法赋值
(该方法无法继承原型链)
//定义一个Person类 function Person(name,age){ this.name=name; this.age=age; }
Person.prototype.getage=function(){ console.log(this.age) }
//定义一个学生类 function Student(name,age,id){ this.id=id; this.methods=Person; this.methods(name,age); delete this.methods; this.getname=function(){ console.log(this.name); } } var studentA=new Student("小王",22,"001");
studentA.getname(); //小王
studentA.getage(); // 报错,没有该方法
上述代码中Student类继承了Person类
2.call继承
实现原理:改变函数内部的函数上下文this,使它指向传入函数的具体对象
(该方法无法继承原型链)
//定义一个Person类 function Person(name,age){ this.name=name; this.age=age; } Person.prototype.getage=function(){ console.log(this.age) } //定义一个学生类 function Student(name,age,id){ this.id=id; Person.call(this,name,age); this.getname=function(){ console.log(this.name); } } var studentA=new Student("小王",22,"001"); studentA.getname(); //小王
studentA.getage(); // 报错,没有该方法
3.apply继承,原理与call类似
(该方法无法继承原型链)
//定义一个Person类
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.getage=function(){
console.log(this.age)
}
//定义一个学生类
function Student(name,age,id){
this.id=id;
Person.apply(this,[name,age]);
this.getname=function(){
console.log(this.name);
}
}
var studentA=new Student("小王",222,"001");
studentA.getname(); //小王
studentA.getage(); // 报错,没有该方法
4.原型链继承
//定义一个Person类
function Person(){
}
Person.prototype.getage=function(){
console.log(this.age)
}
//定义一个学生类
function Student(name,age,id){
this.name=name;
this.age=age;
this.id=id;
this.getname=function(){
console.log(this.name);
}
}
Student.prototype=new Person();
Student.prototype.constructor=Student; //由于上一条代码对Student构造函数原型整个修改了,所以需要修正constructor指向
var studentA=new Student("小王",22,"001");
studentA.getname(); //小王
studentA.getage(); //22
5.采用混合模式实现继承
//定义一个Person类
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.getage=function(){
console.log(this.age)
}
//定义一个学生类
function Student(name,age,id){
Person.call(this,name,age)
this.id=id;
this.getname=function(){
console.log(this.name);
}
}
Student.prototype=new Person();
Student.prototype.constructor=Student; //由于上一条代码对Student构造函数原型整个修改了,所以需要修正constructor指向
var studentA=new Student("小王",22,"001");
studentA.getname(); //小王
studentA.getage(); //22