search

Home  >  Q&A  >  body text

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属性呢?

checkcheck2930 days ago852

reply all(2)I'll reply

  • 数据分析师

    数据分析师2017-10-01 00:39:22

    Why can the instance properties of a subclass in JS access the instance properties of the parent class? -PHP Chinese Q&A-Why can the instance attributes of a subclass in JS access the instance attributes of the parent class? -PHP Chinese website Q&A

    Let’s take a look and learn.

    reply
    0
  • 迷茫

    迷茫2017-03-03 10:54:38

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

    reply
    0
  • Cancelreply