如何避免在JavaScript应用程序中丢失“this”上下文?

这是我的代码示例:

function QueueService() { var key = Config.get("AWS.accessKeyID"); var secret = Config.get("AWS.secretKey"); var credentials = new AWS.Credentials(key, secret, sessionToken = null); this._sqs = new Promise.promisifyAll(new AWS.SQS({apiVersion: '2012-11-05', region: "us-west-2", endpoint: "sqs.us-west-2.amazonaws.com", credentials: credentials})); } QueueService.prototype.FillBirdQueue = function(birds) { var self = this; birds.forEach(function(bird_batch) { var params = { Entries: bird_batch, QueueUrl: Config.get("AWS-Queue.Birds") }; return self._sqs.sendMessageBatchAsync(params); }); }; 

如果我省略var self = this; 并调用return this._sqs.sendMessageBatchAsync(params); 我得到一个错误,因为_.sqs是未定义的。 看起来, this已经改变了,唯一的解决办法就是保存它以备后用var self = this;

我觉得有一个更好的方法去做这件事,但我不完全确定如何使用这些工具在我的处置。 我目前正在使用Bluebird和Lodash,两者都支持绑定。 在过去,我已经通过在Bluebird中执行以下内容来通过this

 somethingAsync().bind(this).then(function(result){}); 

我还没有能够使用这种模式,因为我一开始没有做任何asynchronous。 我只调用一个承诺,并需要能够访问我的构造函数中定义的variables来这样做。

我忽略了一些东西。它可能是什么?