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
});
这是示例函数:
var sampleFunc= function(){
var self = this; //window object
//do something
}
我想在child中获取父级的这个上下文。 但我在那里得到了windows对象。
我试过了:
async.each(smpleArray, sampleFunc, function(err){
// if any of the saves produced an error, err would equal that error
}.bind(this));
但它不起作用。
如何获取父亲的自我/这个内部子功能?
答案 0 :(得分: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
});