我有这个 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
,而不是服务器
如我所愿。
处理此案的最佳模式是什么? _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
,以明确您所指的内容,在调试时可能会错过已使用的局部变量的重新分配很难发现错误。
关于Javascript,嵌套事件处理程序和这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13186490/