从事件发射器设置实例变量

Setting instance variable from event emitter

本文关键字:实例 变量 设置 发射器 事件      更新时间:2023-09-26

所以当我调用下面的代码name的输出值总是"testname"的默认值。应该是"newvalue";

// Constructor
function test(connection) {
    this.name = 'testname';
}
test.prototype.exec = function () {

    var Request = require('tedious').Request // this could be any event emitter;
    request = new Request("select id, name from somevals where id = 1", function (err, rowCount) {
        if (err) {
            console.log(err);
        } else {
            console.log(rowCount + ' rows');
        }
    });

    this.connection.execSql(request);
    request.on('row', function (columns) {
        this.name = 'newvalue'; //how do i  set the instance variable name so that it is visible to the calling module 
    });
};
// export the class
module.exports = test;

调用看起来像

var test = require("./Model/test");
        var b = new test(connection);
        b.exec();
    console.log(b.name);

exec接受回调

// Constructor
function test() {
    this.name = "testname";
}
test.prototype.exec = function (callback) {

    var Request = require('tedious').Request // this could be any event emitter;
    request = new Request("select id, name from somevals where id = 1", function (err, rowCount) {
        if (err) {
            console.log(err);
        } else {
            console.log(rowCount + ' rows');
        }
    });

    this.connection.execSql(request);
    request.on('row', function (columns) {
        callback(columns[1]); //how do i  set the instance variable name so that it is visible to the calling module 
    });
};
// export the class
module.exports = test;

回调定义和测试调用如下

function callback(name) {
    console.log(name);
}
    function executeStatement() {
    var beatle = require("./Model/test");
        var b = new test(connection);
        b.exec(callback);
    console.log(b.name);
    }