简体   繁体   中英

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. But i am getting windows object there.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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