admin管理员组

文章数量:1244221

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 ?

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 ?

Share Improve this question edited Jul 10, 2012 at 21:21 Daniel Li 15.4k6 gold badges44 silver badges60 bronze badges asked Jan 10, 2012 at 22:23 Marc AntoineMarc Antoine 511 silver badge2 bronze badges 1
  • 1 The best thing to do is to have it not be an anonymous function, but instead a function defined with a function declaration statement. – Pointy Commented Jan 10, 2012 at 22:35
Add a ment  | 

3 Answers 3

Reset to default 12

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

Ah... the functional forms of recursion.... [[[flashback to p sci class]]]

You could use a helper function:

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

(which returns 720; this is the factorial function, the canonical example of recursion)

This could in turn be anonymized:

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

or specialized to functions of one argument, to avoid apply and arguments:

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

(both of which also return 720)

This trick of using a helper function allows your function to receive itself as its first argument, and thereby call itself.

To adapt your example:

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

which works as expected in Firebug (logs 0,1,2,3,4,5 to console)

You give a name to anonymous function, here I give it a name "_", although it is named, but it is still anonymous.

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

本文标签: How to make this javascript workStack Overflow