JavaScript继承的实现
JavaScript继承有构造函数继承、原型继承、复制继承、构造函数/原型组合继承等方法,这些继承方法各有特点。眼下最经常使用的就是构造函数/原型组合继承。
/**
* 实现继承
* @param subType {Function} 子类构造函数
* @param superType {Function} 父类构造函数
*/
function inherit(subType, superType){
function F(){}
F.prototype = superType.prototype;
var p = new F();
p.constructor = subType;
subType.prototype = p;
}
/**
* 父类
* @param name {String} 姓名
* @param age {Number} 年龄
*/
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.getName = function(){
return this.name;
};
Person.prototype.setName = function(name){
this.name = name;
};
Person.prototype.getAge = function(){
return this.age;
};
Person.prototype.setAge = function(age){
this.age = age;
};
/**
* 子类
* @param name {String} 姓名
* @param age {Number} 年龄
* @param education {String} 教育程度
*/
function Student(name, age, education){
this.education = education;
//调用父类构造函数
Person.call(this, name, age);
}
//实现继承
//一定要在声明子类原型方法之前,否则会被覆盖。
inherit(Student, Person);
Student.prototype.setEducation = function(education){
this.education = education;
};
Student.prototype.getEducation = function(){
return this.education;
};
var person = new Person('小明', 25);
var student = new Student('小刚', 22, '本科');
person instanceof Person; //true
student instanceof Person; //true
student instanceof Student; //true
父类属性及方法
子类属性及方法