gpt4 book ai didi

javascript - 这个 Node.js 代码似乎替换了同一函数中的函数实现,它有什么作用?

转载 作者:行者123 更新时间:2023-12-03 18:22:59 24 4
gpt4 key购买 nike

我正在尝试调试大量 Node.js 代码,以下内容对我来说看起来很疯狂(因为我的 C++ 和 C# 经验)。有很多函数看起来像这样:

function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}

...我不知道要搜索什么才能获得更多详细信息。

这是我在这里看到的......有一个名为 _builderUtil() 的函数,在它里面有一个 require() 调用,它应该加载一个指定的模块。然后有第二个 _builderUtil 函数内部的东西。它看起来像是一个保存对匿名函数的引用的变量。或者这可能取代了外部函数实现。

这个内部函数(看起来是匿名的)的目的是什么?这段代码有什么作用,它在 Node.js 中是如何调用的,所以我知道要搜索什么?

最佳答案

Or maybe this replaces the outer function implementation.



这就是它正在做的事情。第一次调用 _builderUtil 时,它​​会调用 require 并将结果保存在本地 data 常量中。然后它用一个只返回该 data 常量的函数覆盖执行此操作的函数。 ( data 常量仍然存在,因为内部函数关闭了它。)

基本上,它通过 require 延迟加载数据,然后每次在加载后调用它时返回相同的数据。

正如CertainPerformance 在评论中指出的那样,这是不必要的。 Node.js 的模块系统维护一个加载模块的缓存,因此不需要调用 _builderUtil ,每次需要数据时只使用 require("builder-util") 就足够了。

但是回到它的工作原理并忽略 require 的细节:

最初,您的内存中有这样的内容:

+−−−−−−−−−−−−−−+
_builderUtil−−−−−>| (功能) |
+−−−−−−−−−−−−−−+
| [代码] |
+−−−−−−−−−−−−−−+

第一次调用它时,会为本地人创建一个词法环境对象,以便调用该函数。在那个环境对象中有 data 常量,它是用调用 require 的结果(大概是一些数据)初始化的。在 const data = require("builder-util"); 调用之后和之后的 _builderUtil = 之前,您有:

+−−−−−−−−−−−−−−+
_builderUtil−−−−−>| (功能) |
+−−−−−−−−−−−−−−+
| [代码] |
+−−−−−−−−−−−−−−+

+−−−−−−−−−−−−−−−−+
| (环境对象) |
+−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−+
|数据|------>| (一些数据) |
+−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−+

然后该函数用一个只返回 _builderUtil 的新函数覆盖 data 。函数具有指向创建它们的环境对象的链接,因此一旦调用完成,您将获得:

+−−−−−−−−−−−−−−+
| (功能) | (旧函数,准备被垃圾收集)
+−−−−−−−−−−−−−−+
| [代码] |
+−−−−−−−−−−−−−−+

+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| |
v |
+−−−−−−−−−−−−−−−−+ |
| (环境对象) | |
+−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−+ |
|数据|------>| (一些数据) | |
+−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−+ |
|
+−−−−−−−−−−−−−−−−−+ |
_builderUtil−−−−−>| (功能) | |
+−−−−−−−−−−−−−−−−−+ |
| [环境] |−−−−−−−−−−−−−−−−−−−−−−−−+
| [代码] |
+−−−−−−−−−−−−−−−−−+

最终垃圾收集发生,你刚刚

+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| |
v |
+−−−−−−−−−−−−−−−−+ |
| (环境对象) | |
+−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−+ |
|数据|------>| (一些数据) | |
+−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−+ |
|
+−−−−−−−−−−−−−−−−−+ |
_builderUtil−−−−−>| (功能) | |
+−−−−−−−−−−−−−−−−−+ |
| [环境] |−−−−−−−−−−−−−−−−−−−−−−−−+
| [代码] |
+−−−−−−−−−−−−−−−−−+

关于javascript - 这个 Node.js 代码似乎替换了同一函数中的函数实现,它有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60110627/

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