javascript - Preserve `this` with recursive setImmediate() -
salam (means hello:))
in node.js app, need use setimmediate()
recessively call function , keep context intact next execution.
consider following example:
var i=3; function myfunc(){ console.log(i, this); --i && setimmediate(arguments.callee); } myfunc();
output:
3 // regular `this` object 2 { _idlenext: null, _idleprev: null, _onimmediate: [function: myfunc] } 1 { _idlenext: null, _idleprev: null, _onimmediate: [function: myfunc] }
as can see, after first execution this
overwritten. how should work around this?
do this:
function myfunc(){ console.log(i, this); --i && setimmediate(myfunc.bind(this)); }
as may notice, removed arguments.callee
: its use deprecated , forbidden in strict mode.
Comments
Post a Comment