在node.js中正确使用这个内部回调函数

时间:2014-07-19 20:28:08

标签: javascript node.js callback

在运行'构造函数时,我在访问此类中的变量时遇到错误。脚本。有什么想法吗?

/**
 * 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
        }
    });
};

错误=" TypeError:无法读取属性'表'未定义"

1 个答案:

答案 0 :(得分:1)

您只需要在外部函数中隐藏this,以便回调可以获得正确的值:

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
    }
});

此外,我强烈建议不要使用for ... in循环来迭代查询返回的行。我不熟悉API,但我愿意打赌它是一个真正的JavaScript数组。您应该使用带有索引变量的普通for循环,或者使用.forEach()调用。对于数组使用for ... in是一种不好的做法,原因有几个,其中最重要的是它导致V8(可能还有其他运行时)放弃任何严重优化函数的尝试。在某些情况下代码。其中一种情况是,当你在阵列上使用它时,显然。

相关问题