繁体   English   中英

如何使用对象的属性来设置具有回调函数的另一个属性

[英]how to use an object's properties to set another property with a callback function

认为这是比所关心的许多其他问题不同thisbind 值得注意的是如何在回调中访问正确的`this`上下文?

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

构造函数:

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); 问题不在this问题,而是将值从“回调”中“取出”。

试图保持流程透明,这是第二次尝试:

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

您可以将变量定义为undefined,然后指定一个值。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM