1、原型继承
function Person(name,age){
this.name = name;
this.age = age;
}
function boy(sex){
this.sex = sex;
}
//继承父类的模板和原型对象
boy.prototype = new Person("kk',8);
2、类继承
function Person(name,age){
this.name = name;
this.age = age;
}
function boy(name,age,sex){
this.sex = sex;
Person.call(this,name,age); //以绑定的方式继承父类模板
}
var boy = new boy("ww",3,"男"); //只继承了父类模板,未继承父类原型
3、原型继承+构造函数继承
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.id = 10;
Person.prototype.sayName = function(){}
function boy(name,age,sex){
Person.call(this,name,age); //借用构造函数继承父类模板
this.sex = sex;
}
boy.prototype = new Person();
var boy = new boy("ww",9,"男"); //原型继承,继承父类原型和模板;
// 因为没有传参,所以是屏蔽了模板继承
4、继承方法完整实现
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype = {
constructor: Person;
sayHello :function(){}
};
function Boy(name,age,sex){
Boy.superClass.constructor.call(this,name,age);
this.sex = sex;
}
extend(Boy,Person);//自定义函数
Boy.prototype.sayHello = function(){} //覆盖父类sayHello方法
//自定义函数
function extend(sub,sup){
var F = function(); //创建空函数做中转
F.prototype = sup.prototype; // 实现空函数原型与父类函数原型转换
sub.protype = new F(); // 原型继承
sub.prototype.constructor = Sub; //还原子类构造器
sub.supClass = sup.prototype; //保存父类原型对象
if(sup.prototype.constructor == Object.prototype.constructor){
sup.prototype.constructor = sup; //手动还原父类构造器
}
}
//实现
var b = new Boy("ii",9,"男");
b.sayHello();
BOy.supClass.sayHello.call(b); //访问父类函数