开发者

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

开发者 https://www.devze.com 2023-02-27 20:15 出处:网络
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

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?


That's precisely what the Y combinator is for.

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


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?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号