繁体   English   中英

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

[英]Proper usage of this inside callback function in node.js

运行“构造函数”脚本时,访问此类中的变量时出现错误。 有什么想法吗?

/**
 * 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:无法读取未定义的属性“表”

您只需将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 for数组的使用是一种不好的做法,原因有几个,其中最重要的原因是它在某些情况下会导致V8(以及其他运行时)放弃对函数代码进行认真优化的任何尝试。 。 显然,其中一种情况是在数组上使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM