1

I am using nodejs and mysql client in nodejs I am trying to use pool function od the mysql module.

"use strict";
var mysqlClient = require('mysql')
  , dbPool = mysqlClient.createPool(require('../config/database'));
function MyModel(params) {
  this.tbl = params.tbl;
  this.primary_key = params.primary_key;
  this.primary_name = params.primary_name;
  this.dbPool = dbPool;
}
module.exports = MyModel;
//primary key
MyModel.prototype.fromPK = function fromPK(pk, callback) {
  this.dbPool.getConnection(function (err, connection) {
  var query = "SELECT * FROM " + this.tbl + " WHERE " + this.primary_key + " = " + connection.escape(pk);
    connection.query(query, callback);
  });
};

I know I cannot access this inside getConnection and I could simply set var t = this outside it and access it with var t, but is there any other way to access this var in this condition. Should I define var t = this in each prototype function I write?

I have following detailed gist https://gist.github.com/yalamber/6bd1df0cc27849eb09b3

1 Answer 1

1

You can determine what this is in a function using .bind().

The elaborate syntax is:

var newfunction = oldfunction.bind(THIS_OBJECT);

That would make THIS_OBJECT be the this object inside the oldfunction. As you can see, .bind() returns a new (bound) function.

You don't need that elaborate syntax though, it works on anonymous functions as well:

var newfunction = function() { ... }.bind(THIS_OBJECT);

In your case, you could use this:

this.dbPool.getConnection(function (err, connection) {
  var query = "SELECT * FROM " + this.tbl + " WHERE " + this.primary_name + " = " + connection.escape(pn);
  connection.query(query, callback);
}.bind(this));

This makes the this inside the callback function the same as the this on the outside.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked. Thank you very much. I should keep learning js there are many things to learn here :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.