Javascript实例和这个

我在node.js中写了一个小工具,这是困扰我的部分:

function Active(name, options, data){ events.EventEmitter.call(this); var that = this; that.name = name; that.options = options; that.data = data; that.getData(); that.on('ActiveStart', that.createLogFile); that.on('ActiveDone', that.removeLogFile); function callback() { that.emit('ActiveDone'); } var getData = function() { // starts other processes outside of the scope of this function // callback() gets passed around and called from outside function } getData(); } util.inherits(Active,events.EventEmitter); Active.prototype.createLogFile = function () { this.filename = this.name + '-' + this.options + '.log'; fs.outputFile('./log/' + this.filename,data,function (err) { // fs-extra if(err) return console.log(err); }); }; Active.prototype.removeLogFile = function () { fs.remove('./log/' + this.filename,function (err) { if(err) return console.log(err); }); }; Active.prototype.findData = function () { var that = this; routes.findOneAndUpdate({},update,{sort: _sort},function (err,doc) { // update and _sort are in 'global' scope if(err) return console.log(err); that.emit('ActiveStart',doc.info,doc.data); // the variables are for a different event handler }); }; 

主动有一些其他的方法来解决,我有日志文件的麻烦虽然。 我开始与过程

 new Active('hello','123','data'); 

并创build日志文件。 只要我有一个活动的实例,一切都很好。 如果我开始

 new Active('second','456','moredata'); 

在删除第一个日志之前,removeLogFile稍后删除第二个日志文件,因为this不指向第一个实例,而是第二个日志文件。 这是为什么? 我不是用new操作符创build两个不同的范围吗?

这个值取决于调用者。 避免这个问题的一种方法是使用范围而不是原型inheritance来获得对variables的引用。

 function Active(name, options, data){ events.EventEmitter.call(this); var that = this; that.name = name; that.options = options; that.data = data; that.on('ActiveStart', createLogFile); that.on('ActiveDone', removeLogFile); function createLogFile() { that.filename = that.name + '-' + that.options + '.log'; fs.outputFile('./log/' + that.filename,data,function (err) { // fs-extra if(err) return console.log(err); }); }; function removeLogFile() { fs.remove('./log/' + that.filename,function (err) { if(err) return console.log(err); }); }; } util.inherits(Active,events.EventEmitter);