2017-01-20 23 views
1

I 認爲這與涉及thisbind的許多其他問題不同。值得注意的是How to access the correct `this` context inside a callback?如何使用對象的屬性設置具有回調函數的另一個屬性

我有一個使用該對象屬性的對象上的方法,並進行ajax調用。我希望該值存儲在新的屬性對象中。我只是不確定如何將回調函數分配給屬性。

構造:

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 congressMember(state, district) { 
    this.state = state 
    this.district = district 
} 

方法的回調。

試圖保持過程透明,這裏是一個第二刺:

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

哪些屬性是你試圖設置的? – Agalo

+0

我想添加另一個屬性。我將更新這個問題 – icicleking

回答

0

可以定義一個變量爲未定義,則分配一個值。

var foo; 

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

bar(42) 

console.log(foo) // 42 
+0

這是因爲如果你想從函數或回調中獲取變量,因爲你的問題讓我困惑了一下 –

+0

這是我正在努力掙扎的值的賦值。 – icicleking

0

我在第二個問題實際上刺解決的問題,我很困惑,因爲我是在調用方法後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. 
    }) 
    } 
相關問題