简体   繁体   English

可以在module.exports函数中访问模块中的全局变量吗?

[英]Can function in module.exports access global variable in module?

If I have code like this in one module, 如果我在一个模块中有这样的代码,

var foo = "bar";

module.exports = function() {
    console.log(foo);
}

and I access it from another like so, 我从另一个像这样访问它,

var mod = require('above-module');
mod();

Will it be able to access the variable 'foo' which is local to the module or is it out of scope after 'require' has cached the exported function? 它是否能够访问模块本地的变量'foo',或者在'require'缓存导出的函数后是否超出范围?

Yes you can do this. 是的,你可以这样做。 Typically questions like this are frowned upon because they can be answered more quickly by just trying it out. 通常这样的问题是不受欢迎的,因为通过尝试它们可以更快地回答它们。 You'll get your answer faster that way too 你也可以更快地得到你的答案

Update based on comments: 根据评论更新:

Scenario 1 (no errors) 场景1(没有错误)

Say you have two modules, module A and module B 假设您有两个模块,模块A和模块B.

module A 模块A.

var foo = "bar";

module.exports = function() {
    console.log(foo);
}

module B 模块B.

var mod = require('A');
mod();

If module B is run, "bar" will be logged in the console. 如果运行模块B,将在控制台中记录“bar”。 If you attempt to access module A's foo directly from another module, you will get errors because foo is out of scope. 如果您尝试直接从另一个模块访问模块A的foo,则会出现错误,因为foo超出了范围。

Scenario 2 (undefined errors) 场景2(未定义的错误)

If you try to access foo from module A in another module, there will be errors 如果您尝试从另一个模块中的模块A访问foo,则会出现错误

module C 模块C.

var mod = require('A');
console.log(foo);  //error.  undefined.  foo is out of scope here
console.log(mod.foo);  //also an undefined error

Scenario 3 (Redefining A to allow foo access outside module) 场景3(重新定义A以允许foo访问模块外部)

If you need to have foo accessible outside module A, it needs to be exported. 如果您需要在模块A外部访问foo,则需要将其导出。 Simplest way to do that would be to add it as a property to the exported function 最简单的方法是将其作为属性添加到导出的函数中

Redefined module A 重新定义的模块A.

var foo = "bar";
module.exports = function() {
    console.log(foo);
}

module.exports.foo = foo;

Then you could access like so 然后你可以这样访问

module Accessing foo 模块访问foo

var mod = require('A');
var foo = mod.foo;  //access foo in module A like so

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

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