微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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'

原文地址:https://www.jb51.cc/js/152778.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐