英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论