Javascript, nested eventhandler and this



我有这个JavaScript类:

var Server = (function () {
var spawn = require('child_process').spawn;
function Server(serverDefinition) {
    this.definition = serverDefinition;
    this.status = false;
}
Server.prototype.start = function () {
    this.process = spawn('java', ['-jar', this.definition.jarfile]);
    this.status = true;
    this.process.on('exit', function(code, signal){
        this.status = false;
        console.log('Server stopped: code=' + code + ', signal=' + signal);
    });
    this.process.stdout.on('data', function(data){ console.log('stdout: ' + data);});
    this.process.stderr.on('data', function(data){ console.log('stderr: ' + data);});
};
return Server;

})();

我的问题是this.process.on('exit', ... )内部的this指的是process,而不是我想要的Server

处理这种情况的最佳模式是什么?_self = this?在这种情况下,应该在哪里插入该行,我应该停止参考this,而仅用_self

您可以创建一个局部变量,该变量在函数范围中包含对this的引用,这将起作用,因为在JavaScript中,变量的范围由其源代码中的位置定义,嵌套功能可以访问其外部范围中声明的变量。[1]

Server.prototype.start = function () {
    var serv = this; // Reference to local object for use in inner-functions
    this.process = spawn('java', ['-jar', this.definition.jarfile]);
    this.status = true;
    this.process.on('exit', function(code, signal){
        serv.status = false;
        console.log('Server stopped: code=' + code + ', signal=' + signal);
    });
    this.process.stdout.on('data', function(data){ console.log('stdout: ' + data);});
    this.process.stderr.on('data', function(data){ console.log('stderr: ' + data);});
};

在我看来,最好的做法是在可能的情况下继续引用this,以清楚您所涉及的内容,人们可能会错过对使用的本地变量的重新分配,同时调试很难找到错误。

最新更新