javascript
JavaScript中的全局变量介绍
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:
全局變量在函數(shù)外部聲明,以在整個(gè)程序中進(jìn)行訪問,而局部變量使用var存儲(chǔ)在函數(shù)中,僅在該函數(shù)的范圍內(nèi)使用 。 如果在不使用var情況下聲明變量,即使該變量位于函數(shù)內(nèi)部,則仍將其視為全局變量:
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:
全局變量也是當(dāng)前作用域的對(duì)象,例如瀏覽器窗口:
var dog = “Fluffy”; console.log(dog); // Fluffy;var dog = “Fluffy”; console.log(window.dog); // FluffyIt’s a best practice to minimize global variables. Since the variable can be accessed anywhere in the program, they can cause strange behavior.
最佳做法是最小化全局變量。 由于可以在程序中的任何位置訪問變量,因此它們可能導(dǎo)致奇怪的行為。
References:
參考文獻(xiàn):
var -Javascript|MDN
var -Javascript | MDN
You Don’t Know JavaScript: Scopes & Closures
您不懂JavaScript:范圍和閉包
javascript中的全局變量和window.variable有什么區(qū)別? (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變量的范圍是全局或局部。 全局變量在函數(shù)之外聲明,并且其值在整個(gè)程序中都可以訪問/更改。
You should ALWAYS use var to declare your variables (to make locally) else it will install GLOBALLY
您應(yīng)該始終使用var聲明變量(在本地生成),否則它將全局安裝
Take care with the global variables because they are risky. Most of the time you should use closures to declare your variables. Example:
請(qǐng)注意全局變量,因?yàn)樗鼈兙哂酗L(fēng)險(xiǎn)。 大多數(shù)時(shí)候,您應(yīng)該使用閉包來聲明變量。 例:
(function(){var myVar = true; })();更多信息: (More Information:)
Visual guide to JavaScript variable definitions and scope
可視化JavaScript變量定義和范圍指南
Intro to JavaScript variable definitions and hoisting
JavaScript變量定義和提升簡(jiǎn)介
翻譯自: https://www.freecodecamp.org/news/global-variables-in-javascript-explained/
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的JavaScript中的全局变量介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到自己头发白了好多预示着什么
- 下一篇: JavaScript中的基本表单验证