这个看起来替代了同一函数内部函数实现的Node.js代码有什么作用?

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

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

...,我不知道要搜索什么以获取更多详细信息。

Here's what I see here... There's a function called _builderUtil() and inside it there's a require() call which should load a specified module. Then there's a second _builderUtil something inside the function. It looks like a variable holding a reference to an anonymous function. Or maybe this replaces the outer function implementation.

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

评论
  • 大老公
    大老公 回复
    也许这取代了外部函数的实现。

    That's what it's doing. The first time you call _builderUtil, it does the require call and saves the result in the local data constant. Then it overwrites the function that did that with one that just returns that data constant. (The data constant survives because the inner function closes over it.)

    Basically, it lazy-loads the data via require, then returns the same data every time you call it after it's loaded.