类的继承:当定义一个class的时候,可以从某个现有的class继承,新的class称为子类(Subclass),而被继承的class称为基类、父类或超类(Base class、Super class)。继承有什么好处?最大的好处是子类获得了父类的全部功能。继承的第二个好处需要我们对代码做一点改进。类和类之间的关系。
JavaScript由于采用原型继承,我们无法直接扩展一个Class,因为根本不存在Class这种类型。
原型继承的方式:
1.定义新的构造函数,并在内部用call()
调用希望“继承”的构造函数,并绑定this
;“继承”表示该方式并不是继承关系,只能说是拓展关系。
// 定义构造函数Student
function Student(props) {
this.name = props.name || '匿名'; // 默认值为'匿名'
this.grade = props.grade || 1; // 默认值为1
}
// 使函数共用,减少内存的开销
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};
要基于Student扩展出PrimaryStudent
function PrimaryStudent(props) {
// 调用Student构造函数,绑定this变量:
Student.call(this, props);
this.grade = props.grade || 1;
}
var tobey=new PrimaryStudent();
那么原型链如下:
tobey ----> PrimaryStudent.prototype ----> Object.prototype ----> null
可以看到调用了原先的构造函数Student,并没有继承。只是进行了扩展,真正的继承关系的原型链应该如下所示:
tobey ----> PrimaryStudent.prototype ----> Student.prototype ----> Object.prototype ----> null
如果是继承关系,那么新的基于PrimaryStudent
创建的对象不但能调用PrimaryStudent.prototype
定义的方法,也可以调用Student.prototype
定义的方法。
2.借助中间函数F
实现原型链继承
借助一个中间对象来实现正确的原型链,这个中间对象的原型要指向Student.prototype
。中间对象可以用一个空函数来实现。
// PrimaryStudent构造函数:
function PrimaryStudent(props) {
Student.call(this, props);
this.grade = props.grade || 1;
}
// 定义一个空函数F:
function F() {
}
// 把F的原型指向Student.prototype:
F.prototype = Student.prototype;
// 把PrimaryStudent的原型指向一个新的F对象,F对象的原型正好指向Student.prototype:
PrimaryStudent.prototype = new F();
// 把PrimaryStudent原型的构造函数修复为PrimaryStudent:
PrimaryStudent.prototype.constructor = PrimaryStudent;
// 继续在PrimaryStudent原型(就是new F()对象)上定义方法:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
// 创建xiaoming:
var xiaoming = new PrimaryStudent({
name: '小明',
grade: 2
});
xiaoming.name; // '小明'
xiaoming.grade; // 2
// 验证原型:
xiaoming.__proto__ === PrimaryStudent.prototype; // true
xiaoming.__proto__.__proto__ === Student.prototype; // true
// 验证继承关系:
xiaoming instanceof PrimaryStudent; // true
xiaoming instanceof Student; // true
对象和原型对象的区别在于,原型对象具有constructor属性指向原型对象函数。
3.通过封装的inherits
函数完成原型链继承
如果把继承这个动作用一个inherits()
函数封装起来,还可以隐藏空函数F的
的定义,并简化代码:
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
构造函数Student的定义
function Student(props) {
this.name = props.name || 'Unnamed';
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
构造函数PrimaryStudent的定义
function PrimaryStudent(props) {
Student.call(this, props);
this.grade = props.grade || 1;
}
// 实现原型继承链:
inherits(PrimaryStudent, Student);
// 绑定其他方法到PrimaryStudent原型:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};