Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda