从同一源导入的功能是否可以访问其源全局变量?
好的,我使用我知道的每个关键字搜索了我知道的每个站点,但是我发现没有什么可以关闭的我搜索的主题,也许整个问题是错误的,但是无论如何...
假设我们有一个名为index.js的模块
,其中包含存储
和两个负责读取/写入存储
的功能。
var STORAGE = []
function writeStorage(data) {
STORAGE.push(data)
}
function readStorage(data) {
//find data in STORAGE... and return result as RES
return RES
}
现在,在名为write.js
的文件中,我们导入writestorage()
。
在名为read.js
的另一个文件中,我们导入readstorage()
。
这就是问题上升的地方,
是否会从同一源导入功能,可以访问其源全局变量吗?
ie,我们可以在index中修改
,使用storege
。 JSwritestorage()
我们在write.js
中导入的?
并读取存储
使用read.js
使用readstorage()
?。
OK i searched every site i knew, using every keyword i knew, but i found nothing close the subject i searched about, maybe the whole question is wrong, but anyway...
let's say we have a module named Index.js
, which contains a STORAGE
and two functions responsible for reading/writing to STORAGE
.
var STORAGE = []
function writeStorage(data) {
STORAGE.push(data)
}
function readStorage(data) {
//find data in STORAGE... and return result as RES
return RES
}
Now, inside a file named write.js
, we import writeStorage()
.
While in another file named read.js
, we import readStorage()
.
And this is where the question rises,
Does imported functions from the same source, have access to their source global variables ?
i.e, can we modify STORAGE
in index.js
, using writeStorage()
which we imported in write.js
?
and read STORAGE
changes from read.js
using readStorage()
?.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想为此提供更清晰的答案。功能有两个范围:词汇和动态。 动态表示,一个函数将在该区域中搜索变量,该变量被称为:
词汇表示,该函数将搜索变量,而变量是< Strong>书面/声明:
但是在JavaScript中,无法使用动态范围,因此所有函数都将搜索变量 已声明/书面 。
不要注意细节,这只是一个伪代码。
I want to provide clearer answer about that. There are two scopes for functions: lexical, and dynamic. Dynamic means, a function will search variables in the area, where it was called:
Lexical means, the function will search variables where it was written/declared:
But in JavaScript, there is no way to use dynamic scope, so all function will search variables where it has been declared/written.
DO NOT PAY ATTENTION ON DETAILS, IT'S JUST A PSEUDO-CODE.
简短答案:是的,这是可能的。
Short answer: Yes, that's possible.
是的,您可以做到这一点。
这篇文章也可能有助于理解:
相同的JavaScript分享相同的词汇范围
另一个例子是证明@Azamat的答案
Yes you can do this.
This post might also help in understanding:
Same javascript module imported in different files, sharing the same lexical scope
A further example to demonstrate @Azamat 's answer