开发者

Javascript: Why use an anonymous function here?

开发者 https://www.devze.com 2023-01-04 08:03 出处:网络
I was browsing the JIT\'s code, and I saw this: var isGraph = ($type(json) == \'array\'); var ans = new Graph(this.graphOptions);

I was browsing the JIT's code, and I saw this:

   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;
            };

What could be the purpose for those anonymous functions? They immediately pass out of scope, right?

Why use:

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

instead of:

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

Is this some super elite JS hack?


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.

0

精彩评论

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

关注公众号