2

我正在使用 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();
4

1 回答 1

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除非您在函数中需要它,否则您将不再需要那些愚蠢的 s

于 2013-03-20T01:38:53.993 回答