简体   繁体   English

如何获取父函数这个内部子函数使用async.each

[英]How to get parent function This inside child function using async.each

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
});

This is sample function : 这是示例函数:

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

//do something
}

I want to fetch the parent's this context inside child. 我想在child中获取父级的这个上下文。 But i am getting windows object there. 但我在那里得到了windows对象。

I tried: 我试过了:

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

But its not working. 但它不起作用。

How to get the parent's self/this inside child function ? 如何获得父母的自我/这个内部子功能?

You have to bind the context to the correct function, ie sampleFunc like this: 您必须将上下文绑定到正确的函数,即sampleFunc,如下所示:

sampleFunc.bind(this)

So your example would be: 所以你的例子是:

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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM