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

时间:2014-07-26 18:14:48

标签: javascript node.js

因此,当我调用下面的代码时,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);

1 个答案:

答案 0 :(得分:0)

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

    }