9
I need to instantiate a class from a string.
Turns out for some reason it doesn’t work the way I used to:
class MinhaClasse{
meuMetodo(){
alert('Método Funciona!');
}
}
let nome_classe = 'MinhaClasse';
let nome_metodo = 'meuMetodo';
// var obj = new MinhaClasse(); // instanciando diretamente funciona
var obj = new window[nome_classe](); // instanciando por string não funciona
obj[nome_metodo]();
In Chrome (V75) is returning the following error:
Uncaught Typeerror: window[classname] is not a constructor
class MinhaClasse{
meuMetodo(){
alert('Método Funciona!');
}
}
let nome_classe = 'MinhaClasse';
let nome_metodo = 'meuMetodo';
// var obj = new MinhaClasse(); // instanciando diretamente funciona
var obj = new window[nome_classe](); // instanciando por string não funciona
obj[nome_metodo]();
I also made a JSFIDDLE
NOTE: Observe the application in current browsers (Ex: Chrome V75 or higher), because the solutions given in other answers here are similar to the method I used (described above) and do not work in browsers current.
Did the answer resolve what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?
– Maniero