Pacerier
Pacerier

Reputation: 89763

javascript: how to refer to an anonymous function within the function itself?

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?

Upvotes: 10

Views: 4834

Answers (3)

Jamie Treworgy
Jamie Treworgy

Reputation: 24344

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();

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 360026

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?

Upvotes: 4

Related Questions