I'm getting an error accessing the variables in this class when running a 'constructor' script. Any thoughts?
/**
* Info
*/
exports.sqlWhiteList = function(){
var sqlImport = require('../DBConnectors/MYSQLConn.js');
var sql = new sqlImport.sqlConn();
//fill up static variables
this.tables = {};
this.attributes = {};
//populate the table names
sql.performQuery(('xxxxxx xxxxx = \'BASE TABLE\' ' +
'AND TABLE_SCHEMA=\'' + sql.credentials.database + '\''),function(rows){
for (var index in rows){
this.tables[rows[index]['TABLE_NAME']] = true; // this fails
}
});
};
Error = "TypeError: Cannot read property 'tables' of undefined"
You just need to stash this in the outer function so that the callback can get to the right value:
var moduleObj = this;
// ...
//populate the table names
sql.performQuery(('xxxxxx xxxxx = \'BASE TABLE\' ' +
'AND TABLE_SCHEMA=\'' + sql.credentials.database + '\''),function(rows){
for (var index in rows){
moduleObj.tables[rows[index]['TABLE_NAME']] = true; // this fails
}
});
Also I would very strongly suggest not using a for ... in loop to iterate over the rows returned from the query. I'm not familiar with the API but I'm willing to bet that it's a real JavaScript array. You should use either a plain for loop with an index variable, or else a .forEach() call. Using for ... in for arrays is sort-of a bad practice for a few reasons, not the least of which is that it causes V8 (and maybe other runtimes) to abandon any attempt at serious optimization of a function's code in some cases. One of those cases is when you're using it on an array, apparently.