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/