javascript – Nodejs:在函数调用中包装整个脚本

我一直在nodejs中编写模块如下:
module.exports = function (logger,db,external,constants) {

        return {
           //something

        }
    }

最近我的团队中的某些人建议整个脚本应该包含在一个函数中,以避免全局混淆变量,如下所示:

(function () {
    'use strict';
    module.exports = function (logger,constants) {

        return {
               //something
        }
    }

}());

据我所知,这种做法通常用于客户端代码.但是在nodejs的服务器端这是必需的吗?我认为在nodejs中确实没有全局范围,只有module.exports是可以访问的,无论我们在脚本文件中编写什么(当然不要在这里疯狂).

解决方法

不,Node.js不需要 IIFEs.

它们可用于可能在多个环境中使用的任何脚本(UMD).

但是,Node.js执行的每个模块/文件都有一个“模块范围”,类似于IIFE提供的范围,as described under “Globals”

In browsers,the top-level scope is the global scope. That means that in browsers if you’re in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

尽管如此,Node.js仍然存在全局范围.当模块创建全局时,它将在同一进程使用的其他模块中可访问.

foo = 'bar'; // lack of `var` defines a global

console.log(global.foo); // 'bar'

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...