我正在使用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();
最佳答案
使用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
笨拙的人,除非您在函数中需要它