简体   繁体   English

在nodejs模块中,自执行函数是否被视为一种好的做法?

[英]Is self executing function considered a good practice in nodejs module?

I know that, having self executing function, is a good practice for JavaScript in browser, to avoid variable scoping issue. 我知道,具有自执行功能对于浏览器中的JavaScript来说是一种很好的做法,可以避免变量范围问题。

However, I was wondering, is self executing function still required, in nodejs module? 但是,我想知道,nodejs模块中是否仍需要自执行功能? Or, it is no longer serve the variable scoping purpose? 还是不再满足可变范围的目的?

For instance 例如

screenshot.js (Without self executing function) screenshot.js(没有自我执行功能)

const puppeteer = require('puppeteer');
module.exports = async (url, width, height, path) => {
  ...
  return screenshot;
};

screenshot.js (With self executing function) screenshot.js(具有自动执行功能)

const puppeteer = require('puppeteer');
(function () {
  module.exports = async (url, width, height, path) => {
    ...
    return screenshot;
  };
})();

A regular self executing function expression that you show in your second code block serves no purpose in a node.js module because a node.js module is already wrapped (by node.js) into it's own function, so it already has it's own unique function scope. 您在第二个代码块中显示的常规自执行函数表达式在node.js模块中没有用,因为node.js模块已经被node.js包装到其自身的函数中,因此已经具有其自身的唯一性功能范围。 There is no need to wrap it again to give it another unique function scope. 无需再次包装它以赋予它另一个独特的功能范围。

You can see the actual node.js module wrapper here in the doc . 您可以在doc中查看实际的node.js模块包装器。

(function(exports, require, module, __filename, __dirname) {
    // Module code actually lives in here
});

This wrapper function is what is executed when your module runs and your modules code is inserted into this wrapper before the code is handed to eval() to parse. 该包装函数是在模块运行并将模块代码插入该包装之前执行的,然后将代码交给eval()进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM