Save `this` with recursive setImmediate ()

Salam (means Hello :))

In my application, node.js I need to use setImmediate()to recessively call a function and save its context for the next execution.

Consider the following example:

var i=3;

function myFunc(){
    console.log(i, this);
    --i && setImmediate(arguments.callee);
}

myFunc();

Conclusion:

3 // a regular `this` object
2 { _idleNext: null, _idlePrev: null, _onImmediate: [Function: myFunc] }
1 { _idleNext: null, _idlePrev: null, _onImmediate: [Function: myFunc] }

As you can see, it is thisoverwritten after the first run . How do I get around this?

+4
source share
1 answer

Do it:

function myFunc(){
    console.log(i, this);
    --i && setImmediate(myFunc.bind(this));
}

As you can see, I deleted arguments.callee: its use is outdated and forbidden in strict mode .

+3
source

All Articles