admin管理员组文章数量:1429822
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]);
}
Is this some super elite JS hack?
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]);
}
Is this some super elite JS hack?
Share Improve this question edited Aug 2, 2010 at 1:41 Kevin Hakanson 42.3k23 gold badges130 silver badges158 bronze badges asked Jun 21, 2010 at 4:38 Nick HeinerNick Heiner 123k192 gold badges486 silver badges706 bronze badges1 Answer
Reset to default 12They 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.
本文标签: Javascript Why use an anonymous function hereStack Overflow
版权声明:本文标题:Javascript: Why use an anonymous function here? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745532528a2662125.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论