在JavaScript中,类A是否可以实例化一个继承自A的对象B?

huangapple go评论71阅读模式
英文:

In JavaScript, can a class A instantiate an object B that inherit from A

问题

In JavaScript, JavaScript中,类A能否实例化一个继承自A的对象B

考虑一个类A,它实例化一个来自类B的对象:

import B from "B.js";

export class A {
  constructor() {}
  fct() {
    this.b = new B();
  }
}

B能否继承自类A

import A from "A.js";

export class B extends A {
  constructor() {}
}

请注意,我使用Webpack和ES模块。

英文:

In JavaScript, can a class A instantiate an object B that inherit from A?

Consider a class A that instantiate an object from a class B:

import B from "B.js"

export class A {
  constructor() {}
  fct() {
    this.b = new B();
  }
}

Can the class B inherit from class A?

import A from "A.js"

export class B extends A {
  constructor() {}
}

Note that I use Webpack with ES modules.

答案1

得分: 1

我猜你可以,但有巨大的风险创建一个无限循环:

class A {
  constructor() {
    console.log("我是A")
  }
  fct() {
    this.b = new B();
    // 如果你在这里调用fct,你的浏览器会崩溃
    this.b.fct()
  }
}

class B extends A {
  constructor() {
    super()
    console.log("我是B")
  }
}

let test = new B()
test.fct()
英文:

I guess you can, but there is a huge risk of creating an infinite loop:

class A {
  constructor() {
    console.log("I am A")
  }
  fct() {
    this.b = new B();
    // if you call fct here your browser will crash
    this.b.fct()
  }
}

class B extends A {
  constructor() {
    super()
    console.log("I am B")
  }
}

let test = new B()
test.fct()

huangapple
  • 本文由 发表于 2023年5月22日 18:20:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76305181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定