1

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
Henrique Van Klaveren
  • 1,502
  • 14
  • 24
  • 1
    Just as you do with `array`, make `connection` a property of the instance: `this.connection = ....` and access `this.connection` later. It's exactly how you'd do it without ES6 classes. Nothing has changed in that regard. – Felix Kling Apr 25 '17 at 19:59
  • thats all right \o/, works fine. If you allow me, can I insert blocks of code inside the constructor? Is this way anyway? Thank you – Henrique Van Klaveren Apr 25 '17 at 20:04
  • `this.array = array` you're already doing it :) – niceman Apr 25 '17 at 20:07

1 Answers1

1

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
    })
  }
}
samanime
  • 25,408
  • 15
  • 90
  • 139
  • You're right, it worked perfectly. If you will allow me, I have a question. It is correct to insert my code inside the constructor {}? In this way I inherit for the subclasses that I create later – Henrique Van Klaveren Apr 25 '17 at 20:16
  • It's a bit difficult to say 100%, but in general it could be okay. Just make sure to call `super()` in the function that extends this one and it'll work as expected. – samanime Apr 25 '17 at 20:17
  • Ok, I've seen about super () ... I had not understood where I would place my code, whether below the functions, or inside the same constructor. But as the name suggests CONSTRUCTOR =) half obvious. – Henrique Van Klaveren Apr 25 '17 at 20:21
  • Thank you for your availability. – Henrique Van Klaveren Apr 25 '17 at 20:22