'Is it possible to call an already declared method dynamically from within a class in javascript?
So I have a class with some private methods with the same prefix. And I wanted to do a public method that can call them using the prefix and a suffix with an idea like this :
class MyClass {
#privateMethod1(){
console.log("Hello");
}
#privateMethod2(){
console.log("world");
}
#privateMethod3(){
console.log("!");
}
publicMethod(...names){
names.forEach((name) => {
this.["#privateMethod"+`${name}`]();
});
}
}
let test = new MyClass();
test.publicMethod(1,2,3); // Should display "Hello world!"
But is it even possible? I tried to use objects but nothing seems to work
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
