为什么ES6标准中要在构造函数中给super赋值?它正在为类的实例分配一个值

问题描述 投票:0回答:1

class A {
  constructor() {
    this.x = 1;
  }
}
class B extends A {
  constructor() {
    super();
    this.x = 2;
    super.x = 3;
    console.log(super.x); // undefined
    console.log(this.x); // 3
  }
}
let b = new B();

为什么ES6标准中要在构造函数中给super赋值?它正在为类的实例分配一个值。 为什么

super.x
undefined 
this.x
是3

javascript ecmascript-6 super
1个回答
0
投票
  1. 所有类共享相同的
    this
    (这是与
    new
    一起使用的类的实例),因此在超级构造函数和子构造函数中分配
    this.x = 1
    是相同的。
  2. super
    A.prototype
    的缩写,所以
    super.x
    当然是
    undefined
  3. 要为每个类提供一个道具,您应该使用私有道具,它们就像符号(名称只是代码中的标签)

class A {
  #x;
  constructor() {
    this.#x = 1;
  }
  get x(){ return this.#x }
  set x(v){ this.#x = v }
}
class B extends A {
  x;
  constructor() {
    super();
    this.x = 2;
    super.x = 3;
    console.log(super.x); // undefined
    console.log(this.x); // 3
  }
}
let b = new B();

© www.soinside.com 2019 - 2024. All rights reserved.