I have this javascript class:
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;
})();
My problem is that this
inside of this.process.on('exit', ... )
referes to process
, not Server
as I would like it to.
What is the best pattern of dealing with this case? A _self = this
? In that case, where should that line be inserted, and should I stop referring to this
and only use _self
instead?
You could create a local variable that holds a reference to the this
in the functions scope, this will work because in JavaScript, the scope of a variable is defined by its location within the source code, and nested functions have access to variables declared in their outer scope.[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);});
};
In my opinion it is best practice to keep refering to this
where ever possible to make clear what you are refering to, one might miss a re-assignment of the used local variable while debugging making it hard to find errors.