質問

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, i.e. 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
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top