Node.js - 在回调之间管理javascript范围的更好方法?

时间:2013-03-20 00:57:29

标签: javascript node.js oop events callback

我正在使用Node.JS并且有两个我通过回调移动的对象。我想出了一个解决方案来维护对正确对象的范围引用。我想弄清楚是否有更好的方法来做到这一点,或者这是不是很好的做法。

function Worker () {}

Worker.prototype.receiveJob = function(callback, bossReference) {
  this.doJob(callback, bossReference);
};

Worker.prototype.doJob = function(callback, bossReference) {
  callback.call(bossReference);
  // callback(); // this will not work
};

function Boss () {
  this.worker = new Worker();
}

Boss.prototype.delegateJob = function() {
  this.worker.receiveJob(this.whenJobCompleted, this);
};

Boss.prototype.whenJobCompleted = function() {
  this.sayGoodJob();
};

Boss.prototype.sayGoodJob = function() {
  console.log('Good job');
};

var boss = new Boss();
boss.delegateJob();

1 个答案:

答案 0 :(得分:1)

使用Function.prototype.bind()

function Worker () {}

Worker.prototype.receiveJob = function(callback) {
  this.doJob(callback);
};

Worker.prototype.doJob = function(callback) {
  callback()
};

function Boss () {
  this.worker = new Worker();
}

Boss.prototype.delegateJob = function() {
  this.worker.receiveJob(this.whenJobCompleted.bind(this));
};

Boss.prototype.whenJobCompleted = function() {
  this.sayGoodJob();
};

Boss.prototype.sayGoodJob = function() {
  console.log('Good job');
};

var boss = new Boss();
boss.delegateJob();

除非你在函数中需要它,否则你不需要那些愚蠢的bossReference