Javascript 如何使用对象';s properties以使用回调函数设置另一个属性

Javascript 如何使用对象';s properties以使用回调函数设置另一个属性,javascript,oop,methods,callback,Javascript,Oop,Methods,Callback,我认为这不同于与this和bind相关的许多其他问题。显著地 我在一个对象上有一个使用该对象属性的方法,并进行ajax调用。我希望将该值存储在新的property对象中。我只是不知道如何将回调函数分配给属性 建造商: function congressMember(state, district) { this.state = state this.district = district } 原型上的方法: congressMember.prototype.getMember = fu

我认为这不同于与
this
bind
相关的许多其他问题。显著地

我在一个对象上有一个使用该对象属性的方法,并进行ajax调用。我希望将该值存储在新的property对象中。我只是不知道如何将回调函数分配给属性

建造商:

function congressMember(state, district) {
  this.state = state
  this.district = district
}
原型上的方法:

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
    }
  })
}
然后我想创建一个新实例:
var myHouseRep=new congressMember('WY',1)
问题不在于
,而是从回调中“取出”值

为了使流程保持透明,下面是第二个尝试:

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
    })
  }

可以将变量定义为未定义,然后指定一个值

var foo;

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

bar(42)

console.log(foo) // 42

可以将变量定义为未定义,然后指定一个值

var foo;

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

bar(42)

console.log(foo) // 42

我对这个问题的第二次尝试实际上解决了这个问题,我感到困惑,因为在调用该方法之后,我一直在
console.og
ing

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.
    })
  }

我对这个问题的第二次尝试实际上解决了这个问题,我感到困惑,因为在调用该方法之后,我一直在
console.og
ing

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.
    })
  }

您要设置哪个属性?我想添加另一个属性。我将更新问题您要设置哪个属性?我想添加另一个属性。我将更新问题这是如果你想从函数或回调中获取变量,因为你的问题让我有点困惑,这是我正在努力解决的值的赋值问题。这是如果你想从函数或回调中获取变量,因为你的问题把我弄糊涂了,这是我正在努力解决的价值分配问题。