You don't need eval, you need objects.
"use strict";
const animalClasses = {
Animal: class {
speak() {
return this;
}
},
Wolf: class extends Animal {
speak() {
console.log("Wooooooooo");
return super.speak();
}
}
};
function speakAnimal(classNameStr) {
animalClasses[classNameStr].prototype.speak();
}
However calling methods via the prototype like that is error prone and flat out weird.
We can and should revise it to
function speakAnimal(classNameStr) {
const animal = new animalClasses[classNameStr];
animal.speak();
}
More generally, one would write something like
"use strict";
const createAnimal = (function() {
const animalClasses = {
Animal: class {
speak() {
return this;
}
},
Wolf: class extends Animal {
speak() {
console.log("Wooooooooo");
return super.speak();
}
}
};
return function (animalName) {
return new animalClasses[animalName];
}
}());
And then consume it like this
const name = "Wolf"
const animal = createAnimal(name);
animal.speak();