Javascript:为什么在这里使用匿名函数?

Nic*_*ner 8 javascript anonymous-function

我正在浏览JIT的代码,我看到了这个:

   var isGraph = ($type(json) == 'array');
    var ans = new Graph(this.graphOptions);
    if(!isGraph) 
        //make tree
        (function (ans, json) {
            ans.addNode(json);
            for(var i=0, ch = json.children; i<ch.length; i++) {
                ans.addAdjacence(json, ch[i]);
                arguments.callee(ans, ch[i]);
            }
        })(ans, json);
    else
        //make graph
        (function (ans, json) {
            var getNode = function(id) {
                for(var w=0; w<json.length; w++) { 
                  if(json[w].id == id) {
                    return json[w];
                  }
                }
                return undefined;
            };
Run Code Online (Sandbox Code Playgroud)

那些匿名函数的目的是什么?他们立即超出范围,对吧?

为何使用:

        (function (ans, json) {
            ans.addNode(json);
            for(var i=0, ch = json.children; i<ch.length; i++) {
                ans.addAdjacence(json, ch[i]);
                arguments.callee(ans, ch[i]);
            }
        })(ans, json);
Run Code Online (Sandbox Code Playgroud)

代替:

            ans.addNode(json);
            for(var i=0, ch = json.children; i<ch.length; i++) {
                ans.addAdjacence(json, ch[i]);
                arguments.callee(ans, ch[i]);
            }
Run Code Online (Sandbox Code Playgroud)

这是一些超级精英JS黑客吗?

CMS*_*CMS 12

他们只想在这一小段代码中实现递归:

    (function (ans, json) {
        ans.addNode(json);
        for(var i=0, ch = json.children; i<ch.length; i++) {
            ans.addAdjacence(json, ch[i]);
            arguments.callee(ans, ch[i]); // <-- recursion!
        }
    })(ans, json);
Run Code Online (Sandbox Code Playgroud)

arguments.callee属性引用当前正在执行的函数,如果删除匿名函数,它将引用封闭函数,我不认为他们想再次调用整个函数.

  • @Chaos,是的,是首选方式,在[严格模式]下(http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)`arguments.callee`在ES5上是不允许的...但是使用命名函数表达式*now*会导致问题,因为IE有一个严重的,长期存在的错误,其中函数表达式的标识符缺少封闭范围,实际上,创建了两个函数对象... IE9平台预览中甚至存在错误......悲伤...参见:[命名函数表达式揭秘](http://yura.thinkweb2.com/named-function-expressions/) (2认同)