咏竹莉
where there is a will,there is a way

定义个一个函数,把继承的动作封装起来, 这个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. 继续在新的构造函数的原型上定义新方法

 

posted on 2021-06-30 14:19  咏竹莉  阅读(54)  评论(0)    收藏  举报