The name given to a class expression is intended to allow auto-referencing while the expression is evaluated. That is, while Javascript evaluates the expression to define the value of var Nome
, this variable is not yet a valid class (you cannot reference the value of a variable during its initialization). To circumvent, you can define a "pseudo" name for the class, which will be available only locally relative to the class, which justifies that you cannot instantiate it through this name.
Take an example:
const Classe = class MinhaClasse {
constructor() {
console.log(MinhaClasse.name)
}
}
const objeto = new Classe()
Within the class constructor, to self-reference the "anonymous" class you can use the name given to it. This same name can be obtained by doing Classe.name
, but only as a string. There is no way to instantiate it from this name, because it does not make sense; if you need to instantiate by name, just do not use the class expression, but normally define the named class.
Right, so if I understand correctly, there’s not much point naming a class expression.
– LeAndrade
The function is to allow self-referencing class... first sentence of the answer. If you need to self-reference, you need to name; if you do not need to self-reference, you do not need to name. Simple as that.
– Woss