最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can function in module.exports access global variable in module? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Mar 8, 2016 at 21:39 Suraj asked Mar 8, 2016 at 21:06 SurajSuraj 3194 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

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 ments:

Scenario 1 (no errors)

Say you have two modules, module A and module B

module A

var foo = "bar";

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

module B

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

If module B is run, "bar" will be logged in the console. If you attempt to access module A's foo directly from another module, you will get errors because foo is out of scope.

Scenario 2 (undefined errors)

If you try to access foo from module A in another module, there will be errors

module 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)

If you need to have foo accessible outside module A, it needs to be exported. Simplest way to do that would be to add it as a property to the exported function

Redefined module A

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

module.exports.foo = foo;

Then you could access like so

module Accessing foo

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

评论列表(0)

  1. 暂无评论