JS中子类的实例属性为什么可以访问父类的实例属性?

class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  
  test() { }
}

class Student extends Person {
  constructor(name, age, no) {
    super(name, age)
    this.no = no
  } 

  say() {
    console.log(`name: ${this.name}, age: ${this.age}, no: ${this.no}`)
  }
}

let student = new Student('mrcode', 21, '11403080435')

student.say()

student可以访问test方法,这点可以理解。 但是为什么通过Student中的this可以访问到父类中的name, age呢? ES6中的class只是原型链的语法糖。 原型链上的对象都是原型。 哪里来的name, age属性呢?

阅读 5.2k
5 个回答

翻译过来基本就是这个样子

function Person(name,age){
    this.name=name;
    this.age=age;
}

Person.prototype.test=function(){
    console.log("~~~prototype test~~~")
}

function Student(name,age,no){
    Person.apply(this,[name,age]);//super(name, age)
    this.no=no;
}

//extend
Student.prototype=(function(){
  var tempObject=function(){};
  tempObject.prototype=Person.prototype;
  return new tempObject();
}());
Student.prototype.constructor=Student;
//定义Student类的say函数
Student.prototype.say=function(){
    console.log("name:%s,age:%s,no:%s",this.name,this.age,this.no);
}

var student_instance = new Student('mrcode', 21, '11403080435')

student_instance.say();
student_instance.test();

super(name,age))相当于原始寄生组合继承中的 Person.call(this,name,age)

extends
super

这两个关键字实现继承,可以看一下阮一峰的教程

http://es6.ruanyifeng.com/#docs/class#Class的继承

clipboard.png

ES6的class是语法糖,但不是原型链的语法糖。其背后实现还是通过伪经典继承,调用super关键字,就类似于调用了ES5中的Super.apply(this,arguments)【具体浏览器实现不是这样实现的】

super 就是继承父类的属性

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题