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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/js/152778.html

猜你在找的JavaScript相关文章