2016-05-23 108 views
1

我有一个js对象,我有一个方法调用另一个方法并获得一个promise,但是从.then()中我不能访问成员函数foo()。为什么我不能访问foo()以及如何访问它?这里是我的代码:如何从promise中调用object的方法.then()?

function LoadImageGroupFormat() { 
 
    return new Promise(function(resolve, reject) { 
 
     var xhttp = new XMLHttpRequest(); 
 
     xhttp.open('GET', "imagegroup_format.txt"); 
 
     xhttp.onload = function() { 
 
     if (xhttp.status == 200) resolve(xhttp.responseText); 
 
     else reject(Error(xhttp.statusText)); 
 
     }; 
 
     xhttp.onerror = function() { 
 
     reject(Error("Network Error")); 
 
     }; 
 
     xhttp.send(); 
 
    }); 
 
    } 
 
    //the object 
 
var Registerhandler = { 
 
    imageGroupIndex: 0, 
 

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

 
    GetImageGroupFormat: function() { 
 
    var imageGroupIndex = this.imageGroupIndex; 
 
    LoadImageGroupFormat().then(function(ImageGroup_Format) { 
 
     //Do something with ImageGroup_Format 
 
     imageGroupIndex++; //This works 
 
     foo(); //Doesn't work - undefined 
 
    }, function(error) { 
 
     console.error("Failed to Load ImageGroup Format", error); 
 
    }); 
 
    } 
 
}

感谢有这方面的帮助。

+1

'imageGroupIndex ++;' “作品” 因为你犯了一个局部变量'imageGroupIndex',它不是修改'Registerhandler.imageGroupIndex' –

+0

我将如何修改实例的变量? –

回答

1

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

您还需要使用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); 
    }); 
    } 
} 
1

使用Function.prototype.bind()bind()方法创建新的功能,调用它时,有其this关键字设置为所提供的值,与前面的任何设置参数给定的序列,当新功能被称为。

function LoadImageGroupFormat() { 
 
    return new Promise(function(resolve, reject) { 
 
    resolve('success!'); //updated fro demonstration purpose 
 
    }); 
 
} 
 
var Registerhandler = { 
 
    imageGroupIndex: 0, 
 
    foo: function() { 
 
    alert('In foo!'); 
 
    }, 
 

 
    GetImageGroupFormat: function() { 
 
    var imageGroupIndex = this.imageGroupIndex; 
 
    LoadImageGroupFormat().then(function(ImageGroup_Format) { 
 
     console.log(ImageGroup_Format); 
 
     this.imageGroupIndex++; 
 
     this.foo(); 
 
    }.bind(this), function(error) { 
 
     console.error("Failed to Load ImageGroup Format", error); 
 
    }); 
 
    } 
 
} 
 
Registerhandler.GetImageGroupFormat();

+0

我不认为这会起作用。当你调用'.bind'时,你不在对象的方法中,所以'this'没有被设置为对象。 – Barmar

+0

@Barmar,我提供了一个演示..让我知道它失败.. – Rayon

+0

@Barmar是的,你是。在'GetImageGroupFormat'方法中直接调用'bind'。 –

相关问题