How to access this inside prototype function in js

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 acces 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

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.