Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!