Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

505
Visualizações
(JavaScript) Can't it be declared other than declaring a variable as a constructor in a class?

(I am using google translator)

class User{
    name="tom"
    showName(){
        console.log(this.name)
    }
}
const tom = new User()
console.log(tom.name)

The code above prints Tom . But if I change the second line like this, I get an error.

var name="Tom"
let name="Tom"
const name="Tom"
this.name="Tom"
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The way class field syntax was designed, such a line can do one thing: it assigns to a property of the instance.

this.name = "tom" isn't syntactically permitted because it would have been redundant.

var name = and other variants aren't permitted in that position because those are variable declaration keywords (var, let, const) - which keyword you use has various implications on the scope of the newly created variable, and whether it can be reassigned. But this makes no sense in the context of a class field, because you aren't creating a new identifier, you're assigning to a property of an object.

This

class User{
    name="tom"

is the same as doing

class User{
    constructor() {
        this.name = "tom";
    }

name is not a new variable created in a particular scope - it's only a property, so using var, let, or const when declaring it would mix two entirely separate concepts, and so is forbidden.

So, you can only do

class User{
    name="tom"

(Unless you want the property to be private (only useable from the inside of the class), in which case prefix the property name with a #.)

class User{
    #name="tom"
about 4 years ago · Santiago Trujillo Relatório

0

I think what you wanted in your question is to know another way to declare variables in a js class. So, you can use a constructor to achieve that, something like that:

class User{
    constructor() {
        this.name = "tom"
    }
 
    showName(){
        console.log(this.name)
    }
}
const tom = new User()
console.log(tom.name)

That’ll print "tom" as well.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda