定义个一个函数,把继承的动作封装起来, 这个inherits() 函数可以复用:
function inherits(Child, Parent){ var F = function(){}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; }
function Student(props){ this.name = props.name ? props.name : 'Unnamed'; } Student.prototype.hello = function() { console.log(`Hello ${this.name}`); } function PrimaryStudent(props) { // 调用Student构造函数,绑定this变量 Student.call(this, props); this.grade = props.grade ? props.grade : 1; }
// 实现原型链继承
inherits(PrimaryStudent, Student);
// 绑定其他方法到PrimaryStudent 原型:
PrimaryStudent.prototype.getGrade = function(){
return this.grade;
}
小结:
1. 定义新的构造函数,并在内部用 call() 调用希望“继承”的构造函数,并绑定 this;
2. 借助中间函数F实现原型链继承,最好通过封装的inherits 函数完成;
3. 继续在新的构造函数的原型上定义新方法
浙公网安备 33010602011771号