Javascript:为什么在这里使用匿名函数? [英] Javascript: Why use an anonymous function here?

查看:74
本文介绍了Javascript:为什么在这里使用匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览JIT的代码,并且看到了:

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?

为什么使用:

        (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黑客吗?

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

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

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.

这篇关于Javascript:为什么在这里使用匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆