关于继承

128 阅读1分钟

JS中并没有像基于Java或C++那样的继承,JS中的继承是通过原型链实现的。JS中的任何对象都有一个指向其原型对象的属性,这个原型对象保存了该类对象的共同属性,同时该原型对象作为一个对象,也具有指向它的原型对象的属性,层层向上,最终指向一个null值。

当访问一个对象的属性时,不仅仅在该对象上搜寻,还会搜寻该对象的原型以及原型的原型,层层查找,直至找到匹配的属性或者到达原型链的末端指向null。每个函数都有一个prototype属性,指向一个原型对象,若该函数是一个构造函数,那么它所创造的实例对象也会有一个指向其原型对象的属性,这样就可以实现继承。

下面的代码中实现了Students()继承People ():

function People(name,age,sex){
  this.name=name;
  this.age=age;
  this.sex=sex;
}
People.prototype.eat=function(){
  console.log('我能吃')
}
function Students(name,age,sex,school){
  People.call(this,name,age,sex);
  this.school=school;
}
Students.prototype=Object.create(People.prototype);
Students.prototype.constructor=Students;
Students.prototype.study=function(){
  console.log('我能学习');
}
let student=new Students('xixi',19,'male','清华大学');
student.eat();
student.study();
console.log(student.name);
console.log(student.school);

使用class extends关键字实现继承:

class People{
  constructor(name,age,sex){
    this.name=name;
    this.age=age;
    this.sex=sex;
  }
  eat(){
    console.log('我能吃');
  }
}
class Students extends People{
  constructor(name,age,sex,school){
    super(name,age,sex);
    this.school=school;
  }
  study(){
    console.log('我能学习');
  }
}
let student=new Students('xixi',19,'male','清华大学');
student.eat();
student.study();
console.log(student.name);
console.log(student.school);

如果打印出student对象,可以看到如下结果,即student的原型的constructor指向Students构造函数,原型的原型的constructor指向People构造函数,JavaScript通过这样的原型链实现了继承。