![](/img/trans.png)
[英]ES6 classes: is it possible to access the constructor of a child class from the parent?
[英]Create Child Class From Parent (ES6 Classes in Javascript)
我正在尝试通过以子类型作为参数启动父 class 来创建子(子)class,我想知道如何执行此操作。
例如,假设我有以下起始代码:
class Animal{
constructor(settings){
//parent value
this.name = settings.name;
}
//parent function
sayName(){
console.log(`My name is ${this.name}.`);
}
}
class Frog extends Animal{
constructor(settings){
super(settings);
//child-specific value
this.isTreeFrog = settings.isTreeFrog;
}
//child function
livesInTheForest(){
return this.isTreeFrog;
}
}
class Rabbit extends Animal{ [...] }
class Whale extends Animal{ [...] }
我希望能够写:
let barry = new Animal({
animalType: "frog",
name: "Barry",
isTreeFrog: false
})
(而不是let barry = new Frog({name: "Barry", isTreeFrog: false})
)
让barry
成为一只青蛙,这意味着我可以这样写:
barry.sayName() //should print 'My name is Barry'
console.log(barry.livesInTheForest()) //should print 'false'
我已经尝试了两种不同的方法来实现这一点,但两者都有点老套,并没有完全达到我想要的效果。
第一个涉及在存储孩子的 Animal class 中有一个值。例如,在Animal
的构造函数中,我可能有这样的东西:
if(settings.animalType === "frog"){
this.animal = new Frog(settings);
}else [...] //other animal types
这有两个主要问题:
barry.animal.livesInTheForest()
,这会造成不一致,因为可以在没有.animal
的情况下调用父函数。Frog
)不能再是子类,否则我会得到太多的递归,因为它一直试图用 super() 调用自己。我也想到了第二种方法,它的工作原理是这样的:
在父( Animal
)构造函数中:
//make sure this isn't being called from the child class
if(settings.animalType !== null){
if(settings.animalType === "frog"){
//set settings.animal null to avoid too much recursion
//this means that I can't set this.animalType though, so I can't access barry.animalType
settings.animalType = null;
//Is this something I can do?!
this = new Frog(settings);
} else [...] //other animal types
}
这可行(我认为),但我现在无法将this.animalType
设置为settings.animalType
,这意味着我无法编写barry.animalType
并获取frog
。 此外,这对我来说似乎真的很老套,我忍不住想一定有更好的方法来做到这一点。
class Animal {
static create (settings) {
return new this.subClasses[settings.type](settings)
}
}
class Rabbit extends Animal {}
class Frog extends Animal {}
class Whale extends Animal {}
Animal.subClasses = { frog: Frog, rabbit: Rabbit, whale: Whale }
const animals = ['frog', 'rabbit', 'whale'].map((type) => Animal.create({ type }))
console.log({ animals })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.