What is the purpose of using a name for Javascript class expressions?

Asked

Viewed 45 times

4

When using a class expression nominee in Javascript as in the example, I did not understand how to access _Name, whether it is possible to use it:

let Nome = class _Nome {
  constructor(_nome) { 
    this.nome = _nome;
  }
};

let nome = new Nome('Fulano');
console.log(nome)

let _nome = new _Nome('Ciclano')
console.log(_nome);   // _Nome is not defined

My doubts are:

  • What is the purpose of _Name
  • If it is possible to access _Name, how could I use it

1 answer

5


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.

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.