关于这个主题有一些帖子,但在Promises中找不到解释语境概念的帖子。让我们从一些代码开始(这取自Ember.js模块并简化,但可以是任何支持promises的JS代码):
module.exports = CoreObject.extend({
init: function(pluginOptions, parentObject) {
//These are the properties that I want to access in methods below.
this.parentObject = parentObject;
this.propertyA = pluginOptions.propertyA;
this.propertyB = pluginOptions.propertyB;
},
startProcessing: function(whatToProcess) {
/* The following line does not work which is okay
return this.prepareForProcessing(whatToProcess).then(process).then(postProcess(processedData, this); */
//This line does work, but parameters to then don't work. The result of prepareForProcessing is not passed to process and so on.
return this.prepareForProcessing(whatToProcess).then(this.process).then(this.postProcess);
},
prepareForProcessing: function(whatToProcess) {
//this does not work as 'this' is set to a different context
//What does 'this' refer to here?
//How do I access propertyA, propertyB defined at the beginning of this object?
if(this.propertyA) {
....
}
process: function(preparedData) {
//this does not work either
if(this.propertyB) {
.....
}
}
postProces: function(processedData, options) {
//This should work for obvious reasons but is the best way?
if( options.propertyA) {
......
}
}
}
})
现在,我的问题如下:
我很感激任何帮助&指导。非常感谢你。
答案 0 :(得分:0)
您需要使用Function.prototype.bind
:
this.prepareForProcessing(whatToProcess).then(this.process.bind(this)).then(this.postProcess.bind(this));