日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JavaScript中的全局变量介绍

發布時間:2023/11/29 javascript 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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:

全局變量在函數外部聲明,以在整個程序中進行訪問,而局部變量使用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/

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的JavaScript中的全局变量介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。