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

3

10

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?

Dominican answered 22/4, 2011 at 16:17 Comment(2)
This is not an anonymous function. anonymous functions don't have a handle (like f in your case)Sculpsit
@nEEbz: It's the g that makes it not anonymous. The function in an expression `var f = function() {}`` is anonymous.Basilius
I
5

That's precisely what the Y combinator is for.

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

Interlink answered 22/4, 2011 at 16:27 Comment(2)
The Y combinator seems like overkill here.Oxy
@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.Kneepad
O
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?

Oxy answered 22/4, 2011 at 16:20 Comment(8)
@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..Dominican
@Dominican [citation needed]Oxy
@MattBall iE10 beta has use strict in it. It's beaten chrome/safari.Scruff
@Pacerier: this MDC page makes me think you're remembering incorrectly.Oxy
@Scruff did IE10 fixed this issue?Dominican
@Dominican I don't know. I assume that named function expressions work in IE9 if they don't I'm going to get really angry.Scruff
@Pacerier: function declarations are allowed in global or function code, but not within blocks.Basilius
@Tim which makes perfect sense anyway, since JS only has global and function scopes, not block scopes.Oxy
M
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();
Myke answered 22/4, 2011 at 16:28 Comment(2)
Can't say I'd actually use something like this in real code, but seems like a legit workaround...Myke
Having now just read about "the Y combinator" (first I've ever heard of it) I realize, this is actually much the same thing.Myke

© 2022 - 2024 — McMap. All rights reserved.