gpt4 book ai didi

javascript - `arguments.callee` 是如何引用匿名函数的?

转载 作者:行者123 更新时间:2023-11-30 18:19:17 25 4
gpt4 key购买 nike

需要一个脚本来快速告诉我页面上有多少 html 评论以及它们的内容。使用匿名函数进行递归 DOM 遍历似乎是合适的:

var comments = []; //set up an array where comment contents will be copied to

(function(D) {
if (8===D.nodeType) comments.push(D.nodeValue); //check if node is a comment
D=D.firstChild;
while (D) {
arguments.callee(D); //recursively look for comments...
D=D.nextSibling; //...and remember to iterate over all children of any node
}
})(document);

console.log(comments.join("\r\n")); //list all comments

Fiddle按预期工作,但我很好奇它是否真的 同一个 函数被一遍又一遍地调用,或者是否有多个对调用的原始函数的引用,或者是否有多个相同的函数被调用......毕竟,没有进行命名引用,那么随着遍历的深入,它将如何工作?我想我可以通过添加 the following code 来检查进入 while (D) {...}

//tmpCallee has been declared
if (tmpCallee) {
console.warn(arguments.callee === tmpCallee);//true
/*great, means these should be both pointing to the same function*/
console.log(arguments.callee === arguments.caller);//false
/*wait, what? didn't we just establish above that
all of our functions called recursively would be the same?*/
console.log(arguments.caller);//undefined... but it was called recursively!
console.log(arguments.callee);//prints our function code verbatim as it should
}
tmpCallee = arguments.callee;

我很困惑。 1) 我是否真的一遍又一遍地调用同一个函数,或者是否调用了多个相同的函数,或者是其他东西在起作用? 2) 为什么 arguments.caller 指向我们的函数?它显然是由它调用的——这就是递归的工作方式,不是吗?

最佳答案

am I really calling the same function over and over or are there multiple identical functions called or is something else at play?

是的,你只有一个函数实例,你一直引用它。但是,您正在设置一个调用堆栈,其中将为每次调用保存局部变量(在您的情况下为参数 D)。

why does arguments.caller not point at our function?

arguments 对象上没有caller 属性,它是removed .你可能是说 caller property函数对象,它是非标准的但仍然可用(尽管在严格模式和 argments.callee 中被禁止)。

关于javascript - `arguments.callee` 是如何引用匿名函数的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12477115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com