2014-12-18 2 views
2

'this'를 사용하여 변수에 액세스하려하지만 내 함수가 async.series에 의해 호출되기 때문에 컨텍스트가 변경됩니다. 여기에 내 코드 샘플 :async.series에서 호출 된 프로토 타입 함수에서 'this'사용

var search = function(url) { 
    this.music = url; 
} 

search.prototype.test = function() { 
    async.series({ 
     songId: this.getSongId 
    }, function(err, results) {}); 
}; 

search.prototype.getSongId = function(callback) { 
    console.log(this.music) // Prints 'undefined' 
} 
module.exports = search; 

나는 '정의되지 않은'얻을

var engine = require('./lib/index.js'); 
var search = new engine('test'); 
search.test(); 

하고 있어요입니다. 'this'를 async.series 함수에 바인드 할 수있는 방법이 있습니까? 아니면 그냥 내 값을 인수로 전달해야합니까?

+1

예, 그리고 용어는 완벽했다 : ['.bind()'(https://developer.mozilla.org/en-US/docs/Web/JavaScript/ Reference/Global_Objects/Function/bind) – Pointy

+1

프로토 타입에'test'를 다시 정의했습니다. 왜? – thefourtheye

+0

그 코드를 몇 번 읽는다면, 무슨 일이 일어 났는지 말할 수 없습니다. – Pointy

답변

1

@Pointy가 지적했듯이 .bind()는 실제로 올바른 방법이었습니다. 몇 가지 연구를 한 후 여기 어떻게 내 문제를 해결할 수 있습니다.

search.prototype.test = function() { 
    async.series({ 
     songId: this.getSongId.bind(this) //binding "this" here! 
    }, function(err, results) {}); 
}; 

감사합니다 :)