JS类中的字段挂载到了哪里

JS类中的字段挂载到了哪里

class Person {
  name = 'cinnamon'
  age = 20
  constructor() { this.gender = 0 }
  getInfo() {
    return {
      name: this.name,
      age: this.age,
      gender: this.gender
    }
  }
}
当我尝试从Person.prototype获取name, age, gender字段时,输出为undefined,而且当我通过控制台输出Person.prototype时,里面只有constructor和我定义的getInfo。当我new Person()得到实例时,字段却出现在了实例里。所以问题就在于类中的字段到底放在了哪里,如果不是prototype那其实例是怎么获取字段的。

class Person {
      constructor(name,age) { 
        this.gender = 0;
        this.name = name;
        this.age = age;
       }
      getInfo() {
        return {
          name: this.name,
          age: this.age,
          gender: this.gender
        }
      }
    }

参考一下,如果帮助到你,请采纳

class是es6的语法糖,这是它制定的规则,你明白吧。

img