简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM