1

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
    })
  }
Community
  • 1
  • 1
icicleking
  • 1,029
  • 14
  • 38

2 Answers2

0

You can define a variable as undefined, then assign a value.

var foo;

function bar(baz) {
  this.baz = baz;
  foo = this.baz;
}

bar(42)

console.log(foo) // 42
0

My second stab at the problem actually solves the issue, I was confused because I was console.oging after the call to the method.

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
      console.log(_this) // The object now has the returned value
                         // as a property.
    })
  }
icicleking
  • 1,029
  • 14
  • 38