简体   繁体   English

如何使变量在 JavaScript 中的 scope 之外可访问

[英]How to make variables accessible outside of their scope in JavaScript

I am new to JavaScript and learning about scope.我是 JavaScript 和了解 scope 的新手。 I understand that there is Global Scope and Local Scope, but wanted to know if variables in the Local scope could be made available outside their scope. I understand that there is Global Scope and Local Scope, but wanted to know if variables in the Local scope could be made available outside their scope.

Is this possible, and if so how?这可能吗,如果可以,怎么办?

Thank you to everyone with the quick responses.感谢大家的快速回复。

I'm learning to program and I had an outline made up on topics to research from a programmer.我正在学习编程,并且我有一个关于程序员研究主题的大纲。 They said there is a way and even though it is bad practice, this could be used as a developer tool and there are some scenarios this would be helpful in.他们说有一种方法,即使这是不好的做法,也可以用作开发人员工具,并且在某些情况下会有所帮助。

You can assign them to globalThis (also known as window in the browser and global in node):您可以将它们分配给globalThis (在浏览器中也称为window ,在节点中称为global ):

 function assignGlobal(x) { globalThis.globalVar = x; } console.log(globalThis.globalVar); assignGlobal('foo'); console.log(globalThis.globalVar);

WARNING: This is generally considered bad practice.警告:这通常被认为是不好的做法。 It is usually easy to restructure your code in a way that you don't need to assign to the global scope ever.通常很容易以不需要分配给全局 scope 的方式重构代码。

For debugging you can often call console.log(myObject) and inspect it in your developer console ( f12 in chrome; Ctrl + Shift + k in firefox).对于调试,您通常可以调用console.log(myObject)并在您的开发人员控制台中检查它(在 chrome 中是f12 ;在 firefox 中是Ctrl + Shift + k )。 You can then right click the output and select something like “Store as global variable”:然后,您可以右键单击 output 和 select 类似“存储为全局变量”:

控制台日志

  • Right Click → Save as global variable右键单击→另存为全局变量

另存为全局

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM