2013-11-27 17 views
0
var self= this; //parent function context/this 

async.each(smpleArray, sampleFunc, function(err){ 
// if any of the saves produced an error, err would equal that error 
}); 

這是樣本函數獲得父功能這裏面子函數:如何使用async.each

var sampleFunc= function(){ 
var self = this; //window object 

//do something 
} 

我想獲取父母的孩子裏面這種情況下。 但我在那裏得到Windows對象。

我想:

async.each(smpleArray, sampleFunc, function(err){ 
// if any of the saves produced an error, err would equal that error 
}.bind(this)); 

但它不工作。

如何讓父母的自己/這裏面的孩子功能?

回答

2

你必須結合上下文正確的函數,即sampleFunc這樣的:

sampleFunc.bind(this) 

所以,你的例子是:

var sampleFunc = function() { 
    // this is set to parent function context/this 
    // do something 
}; 

async.each(sampleArray, sampleFunc.bind(this), function (err) { 
    // if any of the saves produced an error, err would equal that error 
}); 
+0

得到它..感謝:-)很多 – robieee

+0

你歡迎;) –