Javascript – How to make this javascript work

anonymousjavascriptthis

I'm trying to make a recursive anonymous function.

Here is the function :

(function (i) {
    console.log(i);
    if (i < 5) this(i + 1)
})(0)

I know "this" is the window object. Is there a way to call the function ?

Best Answer

The arguments.callee property can be used.

(function(i){console.log(i);if(i<5)arguments.callee(i+1)})(0)

Another method to achieve the same functionality is by naming function. Outside the scope, the name will not be available:

(function tmp(i){console.log(i);if(i<5)tmp(i+1)})(0); //OK, runs well
alert(typeof tmp); // Undefined


Note that use of the arguments.callee property is forbidden in strict mode:

"use strict";
(function(){arguments.callee})();

throws:

TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them