11

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?

2
  • 2
    This is not an anonymous function. anonymous functions don't have a handle (like f in your case) Commented Apr 22, 2011 at 16:22
  • 5
    @nEEbz: It's the g that makes it not anonymous. The function in an expression `var f = function() {}`` is anonymous. Commented Apr 22, 2011 at 16:54

3 Answers 3

5

That's precisely what the Y combinator is for.

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

Sign up to request clarification or add additional context in comments.

2 Comments

The Y combinator seems like overkill here.
@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.
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?

8 Comments

@Matt Ball i may have been mistaken, but i remember reading that function declarations (the normal way) is not allowed in ES5 strict unless it is within the "global" scope..
@Pacerier [citation needed]
@MattBall iE10 beta has use strict in it. It's beaten chrome/safari.
@Pacerier: this MDC page makes me think you're remembering incorrectly.
@Pacerier: function declarations are allowed in global or function code, but not within blocks.
|
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();

2 Comments

Can't say I'd actually use something like this in real code, but seems like a legit workaround...
Having now just read about "the Y combinator" (first I've ever heard of it) I realize, this is actually much the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.