本文共 1662 字,大约阅读时间需要 5 分钟。
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 . 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; // local var 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:
参考文献:
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;})();
翻译自:
转载地址:http://elrwd.baihongyu.com/