Javascript 如何称呼对象';在一个promise.then()中使用s方法?

Javascript 如何称呼对象';在一个promise.then()中使用s方法?,javascript,promise,Javascript,Promise,我有一个js对象,我有一个方法调用另一个方法并返回一个承诺,但从.then()中我无法访问成员函数foo()。为什么我不能访问foo()以及如何访问它?这是我的密码: 函数LoadImageGroupFormat(){ 返回新承诺(功能(解决、拒绝){ var xhttp=newXMLHttpRequest(); xhttp.open('GET',“imagegroup_format.txt”); xhttp.onload=函数(){ 如果(xhttp.status==200)解析(xhttp

我有一个js对象,我有一个方法调用另一个方法并返回一个承诺,但从.then()中我无法访问成员函数foo()。为什么我不能访问foo()以及如何访问它?这是我的密码:

函数LoadImageGroupFormat(){
返回新承诺(功能(解决、拒绝){
var xhttp=newXMLHttpRequest();
xhttp.open('GET',“imagegroup_format.txt”);
xhttp.onload=函数(){
如果(xhttp.status==200)解析(xhttp.responseText);
else拒绝(错误(xhttp.statusText));
};
xhttp.onerror=函数(){
拒绝(错误(“网络错误”);
};
xhttp.send();
});
}
//对象
变量寄存器句柄={
imageGroupIndex:0,
foo:function(){
//在这里做点别的
},
GetImageGroupFormat:函数(){
var imageGroupIndex=this.imageGroupIndex;
LoadImageGroupFormat()。然后(函数(ImageGroup_格式){
//使用ImageGroup_格式执行某些操作
imageGroupIndex++;//这很有效
foo();//不工作-未定义
},函数(错误){
console.错误(“加载ImageGroup格式失败”,错误);
});
}

}
foo
是一个属性,而不是函数/变量名,您需要使用属性语法调用它。由于
未保存在闭包中,因此需要定义一个局部闭包变量来保存它

您还需要使用
self.imageGroupIndex
来更新该属性,否则将增加该值的副本

var Registerhandler = {
  imageGroupIndex: 0,

  foo: function() {
    //Do something else here
  },

  GetImageGroupFormat: function() {
    var self = this;
    LoadImageGroupFormat().then(function(ImageGroup_Format) {
      //Do something with ImageGroup_Format
      self.imageGroupIndex++;
      self.foo();
    }, function(error) {
      console.error("Failed to Load ImageGroup Format", error);
    });
  }
}
使用时,
bind()
方法创建一个新函数,该函数在调用时将其
this
关键字设置为提供的值,并在调用新函数时在任何提供的参数之前设置给定的参数序列

函数LoadImageGroupFormat(){
返回新承诺(功能(解决、拒绝){
resolve('success!');//出于演示目的更新
});
}
变量寄存器句柄={
imageGroupIndex:0,
foo:function(){
警惕(用foo!);
},
GetImageGroupFormat:函数(){
var imageGroupIndex=this.imageGroupIndex;
LoadImageGroupFormat()。然后(函数(ImageGroup_格式){
console.log(ImageGroup_格式);
这个.imageGroupIndex++;
this.foo();
}.bind(此)、函数(错误){
console.错误(“加载ImageGroup格式失败”,错误);
});
}
}

Registerhandler.GetImageGroupFormat()
imageGroupIndex++“起作用”因为您创建了一个局部变量
imageGroupIndex
,它没有修改
Registerhandler.imageGroupIndex
如何修改实例的变量?我认为这不起作用。在您调用
.bind
时,您不在对象的方法中,因此
未设置为对象。@Barmar,我提供了一个演示。请告诉我它失败了。@Barmar是的,您是
bind
是在
GetImageGroupFormat
方法中直接调用的。对不起,我读错了,我以为你是在
GetImageGroupFormat
函数上调用
.bind()
,而不是它里面的
.then()
函数。@Barmar,在我最初的回答中,我只是这样做的。。谢谢您的更正:)