How to make this javascript work?

I am 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 that "this" is a window object. Is there a way to call a function?

+5
source share
3 answers

You can use the property arguments.callee.

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

Another way to achieve the same functionality is with a 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


Please note that using the property is arguments.calleeprohibited in strict mode:
"use strict";
(function(){arguments.callee})();

throws:

TypeError: the calling, called, and argument properties may not be available for strict mode functions or argument objects for calling them

+12
source

Ah... .... [[[[flashback to comp sci class]]]

:

function X(f) { return f.apply(this, arguments); }
X(function(me, n) { return n<=1 ? n : n*me(me,n-1); }, 6);

( 720, , )

:

(function (f) { return f.apply(this, arguments); })(
  function(me, n) { return n<=1 ? n : n*me(me,n-1); },
  6);

, apply arguments:

(function (f,x) { return f(f,x); })(
  function(me, n) { return n<=1 ? n : n*me(me,n-1); },
  6);

( 720)

.

:

(function (f,x) { return f(f,x); })(
  function(me, i) { console.log(i); if (i<5) me(me,i+1); },
  0)

Firebug ( 0,1,2,3,4,5 )

+1

You specify the name of the anonymous function, here I give it the name "_", although it is named, but it is still anonymous.

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

All Articles