JS 类扩展

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

你能解释一下为什么这段代码会console.log:

B A
B B

我不太清楚构造函数和 super() 在这种情况下是如何工作的

class A {
    constructor(){
        this.name = 'A'
        this.getName()
    }
    getName() {
        console.log("A " + this.name)
    }
}

class B extends A {
    constructor(){
        super();
        this.name = "B";
        this.getName()
    }
    getName(){
        console.log("B " + this.name)
    }
}

new B

javascript class
2个回答
0
投票

第一个“B A”,因为 super() 调用 A 的构造函数,该构造函数记录“A”,后跟 this.name 的值,即“A”。然后是“B B”,因为 B 的构造函数将 name 设置为“B”并记录“B”,后跟 this.name 的值,即“B”。


0
投票

TL;DR 要记住的关键一点是,

this
指的是 class B
实例,而不是
class A
(即使在调用
super()
时)。因此
this.getName()
将调用 B 类中定义的方法,而 A 类中的方法将被忽略。

按时间顺序思考这段代码很有用。以下是发生的情况的概要:

  1. 这两个类都使用各自的方法进行声明。
  2. new B
    调用
    constructor
     中的 
    B
  3. 调用
  4. super()
    ,调用
    constructor
     中的 
    A
  5. this.name = 'A'
    name
    属性设置为
    A
  6. this.getName()
    中的
    A
    调用
    getName
    中的
    B
    (记住:
    this
    指的是
    class B
    的实例,而不是
    class A
    )。
  7. getName
    来自
    B
    输出“B A”(回想一下,
    this.name
    仍然是步骤 4 中的“A”)
  8. A
    constructor
    完成了,我们回到
    B
    的构造函数
  9. this.name = 'B'
    name
    属性设置为
    B
  10. this.getName()
    getName
    调用
    B
    (记住:
    this
    指的是
    class B
    的实例)
  11. getName
    来自
    B
    输出“B B”(回想一下,
    this.name
    是步骤 8 中的“B”)
  12. B的构造函数返回,程序退出
© www.soinside.com 2019 - 2024. All rights reserved.