8

我正在浏览 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;
            };

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

为什么使用:

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

代替:

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

这是一些超级精英 JS hack 吗?

4

1 回答 1

12

They just want to implement recursion in that small piece of code:

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

The arguments.callee property refers to the currently executing function, if you remove the anonymous function, it will refer to the enclosing function, and I don't think they want to invoke the whole function again.

于 2010-06-21T04:41:54.067 回答