什么是nodejs文件中的函数的上下文?
什么是nodejs文件中的函数的上下文? 如果我需要导出function,我只写
module.exports = function () {}; or module.someFunction = function () {};
但是什么情况下没有模块的function呢?
function someFunction () {}; console.log(module); // not someFunction console.log(module.exports); // not someFunction
PS我在哪里可以看到这个文件中声明的函数列表? 在浏览器中,我有window
。 在nodejs中我有global
, module
, module.exports
,但没有一个它没有声明的function。
但是什么情况下没有模块的function呢?
和普通的JavaScript函数一样。 在严格模式下,上下文将是undefined
(function() { 'use strict'; console.log(this === undefined); })(); // true
和马虎模式(非严格模式)的全局对象。
(function() { console.log(this === global); })(); // true
注意:如果你想知道this
是什么,在模块级别,它将是exports
对象。 详细的解释可以在这个答案中find。