[英]Read/Use variables from another javascript file
If I import a js file like this :如果我导入这样的 js 文件:
const importedFile = require( './file1');
I can see all my functions and console logs of file1 running, but I can't run or use a specific variable我可以看到正在运行的 file1 的所有函数和控制台日志,但我无法运行或使用特定变量
If I console.log( importedFile )
I get this : {}
empty object !如果我
console.log( importedFile )
我得到这个: {}
空对象!
How to get all variables from file1.js ?如何从 file1.js 获取所有变量?
JavaScript modules are self-contained environments with their own scope. JavaScript 模块是具有自己作用域的自包含环境。
Only explicitly exported values are available outside of the module.只有显式导出的值在模块外部可用。
So, if you want something in ./file1
to be available in importedFile
, then you need to include it in the exports:所以,如果你想要的东西在
./file1
为处于可用importedFile
,那么你就需要把它列入出口:
const value = "Hello, world";
function thisIsAFunction() {
console.log(value);
}
module.exports = {
thisIsAFunction
}
Then you can:然后你可以:
const importedFile = require( './file1');
importedFile.thisIsAFunction();
I figured it out, in file1 I can export variables like this :我想通了,在 file1 中我可以导出这样的变量:
function thisIsAFunction() {
let var1 = { qty: 123 }
let var2 = { qty: 123 }
let var3 = { qty: 123 }
return [ var1, var2, var3 ];
}
module.exports = {
thisIsAFunction
}
Then read/use the first variable like this:然后像这样读取/使用第一个变量:
let importedValue= importedFunct.thisIsAFunction()
console.log( importedValue[0][0].qty)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.