9

if arguments.callee is not allowed in "use strict", and we can't do

var f = function g() {
    //g
}

because in IE that wouldn't work (or that would work "weirdly") http://kangax.github.com/nfe/#jscript-bugs, then what other options do we have to refer to the anonymous function within the function itself?

Pacerier
  • 86,231
  • 106
  • 366
  • 634
  • 2
    This is not an anonymous function. anonymous functions don't have a handle (like `f` in your case) – neebz Apr 22 '11 at 16:22
  • 5
    @nEEbz: It's the `g` that makes it not anonymous. The function in an expression `var f = function() {}`` is anonymous. – Tim Down Apr 22 '11 at 16:54

3 Answers3

5

That's precisely what the Y combinator is for.

Here's an article by James Coglan about deriving the Y combinator in JavaScript.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 1
    The Y combinator seems like overkill here. – Matt Ball Apr 22 '11 at 16:35
  • @Matt Ball: it's a generic solution to this problem that not only works for JavaScript but for *any* language. @jamietre's solution, for example, looks basically like an idiomatic JavaScript implementation of the Y combinator with some inlining applied. I doubt you can come up with such a trick yourself if you've never heard of the Y combinator. – Jörg W Mittag Apr 22 '11 at 16:48
4

Don't use a named function expression. Just declare and initialize it the normal way.

function f() {
    f();
}

The only viable alternative with ES5 strict is to use the code in your question, and deal with IE's crappy NFE implementation. But: do you really expect a browser that gets NFEs so horribly wrong (ahem, IE) to implement "use strict" anytime soon?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

Here's a rather convoluted way to do it, but it works:

http://jsfiddle.net/4KKFN/4/

var f = function() {
    function f() {
        if (confirm('Keep going?')) {
            this.apply(this);
        }
    }
    f.apply(f);
}

f();
Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119