I think this is different than the many other questions which are concerned with this
and bind
. Notably How to access the correct `this` context inside a callback?
I have a method on an object that uses that objects properties, and makes an ajax call. I want that value then stored in a new property object. I'm just not sure how to assign the callback function to the property.
Constructor:
function congressMember(state, district) {
this.state = state
this.district = district
}
Method on the prototype:
congressMember.prototype.getMember =
function() {
govTrack.findRole({ current: true, state: this.state, district: this.district }, function(err, res) {
if (!err) {
return res.objects[0].person // this won't work
}
})
}
And then I want to make a new instance: var myHouseRep = new congressMember('WY', 1);
The issue isn't with this
but instead getting the value "out of" the callback.
Trying to keep the process transparent, here is a second stab:
function foo(state, district, fn) {
govTrack.findRole({ current: true, state: state, district: district }, function(err, res) {
if (!err) {
fn(res.objects[0].person)
} else {
console.log('error')
}
})
}
congressMember.prototype.getDetails =
function() {
_this = this
foo(this.state, this.district, function(cb) {
_this.details = cb
})
}