2017-01-20 1 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 
} 

방법 of "콜백. 정의되지 않은, 다음 값을 할당으로

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. 
    }) 
    } 
관련 문제