[英]node “require” hoisted to top outside of script — loses access to variables from outer function
我在節點的主腳本頂部需要其他文件。 我所有的require語句都放在頂部。 這就產生了一個問題,因為在調用這些導入腳本中的方法時,它們無權訪問在其中調用它們的函數(因為由於提升問題,不可避免地在這些函數之外定義了它們)。 因此,我必須始終在選項對象中傳遞變量。 有沒有人遇到過類似的問題? 人們使用某種標准的解決方法嗎? 謝謝!
function outer(){ //let's pretend we're in a node environment //this required script will get hoisted to the very top and therefore lose access to the "something" variable! var common = require('../globals/common.js'); var something = "something"; common.printsomething();//will return "something is not defined" }; outer();
嗯
我認為最終將“某種東西”傳遞給printsomething方法會更好,就像這樣。
common.printfoo('bar'); //returns 'bar'
通常,您在做什么並沒有節點中模塊的工作方式。 是的,將大型程序分解為單獨的文件是組織項目的絕佳方法,但恐怕我不得不說您在這里做錯了。 在“外部”的情況下,您可以執行以下操作:
/*script.js*/
var common = require('../globals/common.js');
function outer(str){
common.printsomething(str);//will return "something"
};
var something = 'something';
outer(something);
/*common.js*/
function printthing(str){
console.log(str);
}
module.exports = {
printsomething: function(str){
printthing(str)
}
}
module.js:
module.exports.print = function (data) {
console.log(data);
}
module.exports.add = function (a, b, callback) {
callback(a + b);
}
main.js
var mymodule = require('module');
module.print('Some data'); //Will print "Some data" in the console
module.add(25, 12, function (result) {
console.log(result); //Will print 37
});
如您所見,在main.js中,我不需要知道wrk的module.js的內容。 這就是模塊的目標:將硬邏輯放在其他地方,以構建更好的代碼。 諸如async或fs之類的模塊既龐大又復雜,但是我只需要導入它們即可使用它,而無需知道它是如何做到的。
在構建自己的模塊時,請將其視為一個新的工具庫,以便您可以在另一個項目中重用它,而無需設置使用它們的特定變量。 試想一下,混亂這將是如果兩個模塊都能夠找到你的VAR的內容something
不相關的目標!
模塊是獨立的,可以重復使用。 這些的“吊裝”將降低其功效。
編輯:
如果您有很多環境變量,則可以嘗試使用一種模式,在該模式中將其一次在模塊中進行設置,但是必須確保提供一種與它們進行交互的方式。
模塊:
var data = {};
function set(key, value) {
data[key] = value;
}
function get(key) {
return data[key];
}
function print(key) {
console.log(data[key]);
}
function add(keyA, keyB) {
return data[keyA] + data[keyB];
}
module.exports = {
set: set,
get: get,
print: print,
add: add
};
main.js
var mymod = require('mymod');
mymod.set('data', 'something');
mymod.set('a', 25);
mymod.set('b', 12);
mymod.print('data'); //Print "something"
var c = mymod.add('a', 'b');
console.log(c); //Print 32
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.