在实例中调用属性

时间:2018-05-16 13:55:35

标签: javascript node.js

我试图通过执行sendError来调用我的函数this.instance.sendError,但是我收到如下所示的错误。从报告中我可以看到它指向的两行。我想问题是我创建了DatabaseController,但我似乎无法理解问题所在。有人可以给我解释为什么会这样吗?通过构建这样的DatabaseController是否有效?

SocketHelper.js:12:27
DatabaseController.js:22:24
  

TypeError:无法读取属性' sendError'未定义的

function SocketHelper(io, socket){
    this.io = io;
    this.socket = socket;
    this.instance = this;
}

SocketHelper.prototype.getUserById = function(id, callback){
    DatabaseController.databaseQuery("SELECT * FROM users WHERE id = ?", id, function (error, user) {
        if(error || !user.length > 0) {
            return this.instance.sendError("Couldn't find a user with ID: " + id);
        }
        return callback(null, user[0]);
    });
};

module.exports = function (io) {

    io.on('connection', function (socket) {
        var helper = new SocketHelper(io, socket);
        require('./chathelp.js')(socket, io, helper);
    });
};

chathelp.js

module.exports = function (socket, io, controller) {
    socket.on('userinfo', function () {
        controller.getUser(function(error, user){});
    });
}

DatabaseController

var createDatabaseConnection = function (callback) {
    pool.getConnection(function (error, connection) {
        if(error){
            return callback(error);
        }
        return callback(null, connection);
    });
};

var databaseQuery = function (query, parameters, callback) {
    createDatabaseConnection(function (error, connection) {
        if(error){
            return callback(error);
        }
        if(parameters){
            query = mysql.format(query, parameters);
            connection.query(query, function (error, result) {
                connection.release();
                if(error){
                    return callback(error);
                }
                return callback(null, result);
            });
        } else {
            connection.query(query, function (error, result) {
                connection.release();
                if(error){
                    return callback(error);
                }
                return callback(null, result);
            });
        }
    });
};

module.exports = {
    createDatabaseConnection: createDatabaseConnection,
    databaseQuery: databaseQuery
};

0 个答案:

没有答案