[英]Can function in module.exports access global variable in module?
如果我在一個模塊中有這樣的代碼,
var foo = "bar";
module.exports = function() {
console.log(foo);
}
我從另一個像這樣訪問它,
var mod = require('above-module');
mod();
它是否能夠訪問模塊本地的變量'foo',或者在'require'緩存導出的函數后是否超出范圍?
是的,你可以這樣做。 通常這樣的問題是不受歡迎的,因為通過嘗試它們可以更快地回答它們。 你也可以更快地得到你的答案
根據評論更新:
假設您有兩個模塊,模塊A和模塊B.
模塊A.
var foo = "bar";
module.exports = function() {
console.log(foo);
}
模塊B.
var mod = require('A');
mod();
如果運行模塊B,將在控制台中記錄“bar”。 如果您嘗試直接從另一個模塊訪問模塊A的foo,則會出現錯誤,因為foo超出了范圍。
如果您嘗試從另一個模塊中的模塊A訪問foo,則會出現錯誤
模塊C.
var mod = require('A');
console.log(foo); //error. undefined. foo is out of scope here
console.log(mod.foo); //also an undefined error
如果您需要在模塊A外部訪問foo,則需要將其導出。 最簡單的方法是將其作為屬性添加到導出的函數中
重新定義的模塊A.
var foo = "bar";
module.exports = function() {
console.log(foo);
}
module.exports.foo = 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.