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

155
Visualizações
ECS6 How define/create new an Object inside a Class

I'm beginner in em ES6, and I need instantiate new objects inside a class. How the best way to make this, and how I can access "in this case" the connection in the function getName().

Probably talking nonsense, but I need to understand how this works to evolve. Anyone would have any tips for me.

above little exemple

class Test {
  constructor(array){
    this.array = array

    // CONNECT DATABASE
    var connection = mysql.createConnection({this.array})

  }
  getName(){
    query = 'SELECT * FROM mytable LIMIT 1'
    connection.query(query, function (err, rows, fields) {
      return rows
    })
  }
}


array = {
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'mydb'
}

let T = new Test(array)

T.getName()
// error connection is not defined
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In this example, var connection is a variable that's only in the context of the constructor.

You need to use this.connection to have it actually be a member of the object itself. Change it to this.connection in all places you use it. You don't need a var, let or const when defining a variable like this.

class Test {
  constructor(array){
    this.array = array

    // CONNECT DATABASE
    this.connection = mysql.createConnection({this.array})

  }
  getName(){
    query = 'SELECT * FROM mytable LIMIT 1'
    this.connection.query(query, function (err, rows, fields) {
      return rows
    })
  }
}
over 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