邮箱或手机号 | 密码 | |
忘记帐户? |
注册
无法处理你的请求
此请求遇到了问题。我们会尽快将它修复。
返回首页
- 中文(简体)
- English (US)
- 日本語
- 한국어
- Français (France)
- Bahasa Indonesia
- Polski
- Español
- Português (Brasil)
- Deutsch
- Italiano
- 注册
- 登录
- Messenger
- Facebook Lite
- Watch
- 地点
- 游戏
- Marketplace
- Meta Pay
- Oculus
- Portal
- Bulletin
- 本地
- 筹款活动
- 服务
- 选民信息中心
- 小组
- 关于
- 创建广告
- 创建公共主页
- 开发者
- 招聘信息
- 隐私权政策
- Cookie
- Ad Choices
- 条款
- 帮助中心
- 联系人上传和非用户
- 设置
- 动态记录
Meta © 2022
I have two files that both need a global variable. I have a click button. When it's clicked, runs a function. The code looks like this:
file1:
var globalVar = '', // The global variable <button onClick = {() => this.edit(arg1)}></button> function edit (arg1){ globalVar = arg1; } module.exports = globalVar;I have another file, looks like this:
file2:
var globalVar = require(./file1); function openModal(){ if (globarVar != ''){ do something}
}
The issue is that when I click button, the globalVar is updated in the edit() function, but I console.log(globalVar) in file2 it shows ' '.My question is how do I pass the globalVar to file2 when I click the button?
Global variables in Javascript across multiple files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<h2>Example of JS Global Variable</h2> | |
<p>Using variable from one JS file to another.</p> | |
<p>Open the console to view the output.</p> | |
<p id="demo"> | |
<script type="text/javascript"> | |
var globalvar = false; | |
</script> | |
<script type='text/javascript' src='script.js'></script> | |
<script> | |
console.log(globalvar); | |
document.getElementById('demo').innerHTML = globalvar; | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Sometimes, we want to share variables between files in Node.js.
In this article, we’ll look at how to share variables between files in Node.js.
How to share variables between files in Node.js?
To share variables between files in Node.js, we export the variables and then import them where we want to use them.
For instance, we write
module.js
const name = "foobar"; exports.name = name;to export the name variable with
exports.name = name;Then we import module.js and use name in main.js with
const myModule = require("./module"); const name = myModule.name;Conclusion
To share variables between files in Node.js, we export the variables and then import them where we want to use them.
Web developer specializing in React, Vue, and front end development.
View Archive