Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var
for use only within that function’s scope. If you declare a variable without using var
, even if it’s inside a function, it will still be seen as global:
全局变量在函数外部声明,以在整个程序中进行访问,而局部变量使用var
存储在函数中,仅在该函数的范围内使用 。 如果在不使用var
情况下声明变量,即使该变量位于函数内部,则仍将其视为全局变量:
var x = 5; // globalfunction someThing(y) {var z = x + y;console.log(z);
}function someThing(y) {x = 5; // still global!var z = x + y;console.log(z);
}function someThing(y) {var x = 5; // localvar z = x + y;console.log(z);
}
A global variable is also an object of the current scope, such as the browser window:
全局变量也是当前作用域的对象,例如浏览器窗口:
var dog = “Fluffy”;
console.log(dog); // Fluffy;var dog = “Fluffy”;
console.log(window.dog); // Fluffy
It’s a best practice to minimize global variables. Since the variable can be accessed anywhere in the program, they can cause strange behavior.
最佳做法是最小化全局变量。 由于可以在程序中的任何位置访问变量,因此它们可能导致奇怪的行为。
References:
参考文献:
var -Javascript|MDN
var -Javascript | MDN
You Don’t Know JavaScript: Scopes & Closures
您不懂JavaScript:范围和闭包
javascript中的全局变量和window.variable有什么区别? (What’s the difference between a global var and a window.variable in javascript?)
The scope of JavaScript variables are either global or local. Global variables are declared OUTSIDE the function and its value is accessible/changeable throughout the program.
JavaScript变量的范围是全局或局部。 全局变量在函数之外声明,并且其值在整个程序中都可以访问/更改。
You should ALWAYS use var to declare your variables (to make locally) else it will install GLOBALLY
您应该始终使用var声明变量(在本地生成),否则它将全局安装
Take care with the global variables because they are risky. Most of the time you should use closures to declare your variables. Example:
请注意全局变量,因为它们具有风险。 大多数时候,您应该使用闭包来声明变量。 例:
(function(){var myVar = true;
})();
更多信息: (More Information:)
Visual guide to JavaScript variable definitions and scope
可视化JavaScript变量定义和范围指南
Intro to JavaScript variable definitions and hoisting
JavaScript变量定义和提升简介
翻译自: https://www.freecodecamp.org/news/global-variables-in-javascript-explained/