Home > Enterprise >  Does mysql.createConnection() create an object?
Does mysql.createConnection() create an object?

Time:12-13

In this Node.js example from W3school, does createConnection() create a new object?

If yes, how object isn't created in one of the ways we create a new object; not object literal, not by using new keyword, not by using object.create().

If no, what's con.connect()? Isn't connect() a method of con object ?

Example :

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

CodePudding user response:

If you check the mysql code, you will see createConnection helps set configuration for mysql connection and returns the connection object. You don't need to create a new object as it returns one.

const connection = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});

createConnection is a function which uses new operator and returns the connection object. It will return the new object every time you call it.

If no, what's con.connect()? Isn't connect() a method of con object ?

Yes, it is a method on con object which is attached on its prototype. So, all the connection object will have it.

Also, I recommend you checking this link, it is the index.js of mysql npm package and look how it is returning new connection object.

  • Related