javascript - Node 的 module.exports 和 IIFE 混淆

标签 javascript node.js iife

我一直在研究 Node 和 Javascript IIFE,我对 Node 的 modules.exports 以及 IIFE 在 Javascript 中的工作方式有点困惑。

(function (Calculator) {
    var calculator = function () {
        var currentValue = 0,

            add = function (num) {
                return currentValue += num;
            };

        return {
            current: currentValue,
            add: add
        };
    }();

    module.exports = calculator;
}(module.exports));

当我使用 module.exports = calculator; 行导出模块时,上面的代码导致我的测试通过。

为什么当我使用参数 Calculator = calculator(注意大小写)导致我的测试全部失败?

我以为Calculator(参数)指的是module.exports(传入的值?

简而言之:

计算器=计算器;//不起作用

module.exports = 计算器;//有效

最佳答案

我觉得这很有趣,所以我要添加它。 @dandavis 关于他们是一样的是正确的。但我刚刚通过使用它发现您可以从传入的值更改全局。下面确实将 calculator 作为全局 module.exports 的值。 至少它对我正在玩的这个 gulp 东西有用。虽然我不是 Node 专家,所以在真正的 Node 服务器领域可能有所不同。

(function (Calculator) {
    var calculator = function() {
        var currentValue = 0,

            add = function(num) {
                return currentValue += num;
            };

        return {
            current: currentValue,
            add: add
        };
    }();

    Calculator.exports = calculator;

})(module);

关于javascript - Node 的 module.exports 和 IIFE 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25351695/

相关文章:

javascript - 对象 HTMLAnchorElement] 没有方法 'attr'

javascript - HEROKU 上的 CORS 问题

javascript - 立即调用的函数表达式运行最后定义的函数。为什么?

javascript - 为什么 ViewChild ElementRef 在 ngAfterViewInit 中的宽度和高度为 0?

javascript - 将 jquery + Bootstrap modal-dialog div 更改为 BootStrap + angularjs

javascript - 在 Javascript 中重启生成器

node.js - Npm 安装失败,docker buildx linux/arm64

javascript - IIFE 如何保护命名空间?

JavaScript:setTimeout 不更新循环内的值

java - Google map API 街道长度