搜尋
首頁web前端js教程javascript中的變數作用域以及變數提升詳細介紹_javascript技巧

變數作用域
「一個變數的作用域表示這個變數存在的上下文。它指定了你可以存取哪些變數以及你是否有權限存取某個變數。」

變數作用域分為局部作用域和全域作用域。

局部變數(處於函數層級的作用域)
不像其他對面物件的程式語言(比方說C ,Java等等),javascript沒有區塊級作用域(被花括號包圍的);當是,javascript有擁有函數層級的作用域,也就是說,在一個函數內定義的變數只能在函數內部存取或是這個函數內部的函數存取(閉包除外,這個我們幾天後再寫個專題)。

函數層級作用域的一個例子:


複製程式碼 程式碼如下:

var name = "Richard"; >
function showName () {
    var name = "Jack"; // local variable; only accessible in this showName function
    console.log (name); //> Jack
    console.log (name); console.log (name); // Richard: the global variable

沒有區塊級作用域:


複製程式碼 程式碼如下:
var name = "Richard"; >// the blocks in this if statement do not create a local context for the name variable
if (name) {
    name = "Jack"; // this name is the global name variable and it is being"; // this name is the global name variable and it is being change to "Jack" here
    console.log (name); // Jack: still the global variable
}

// Here, the name variable is the same global name variable, but it was changed in the if statement
console.log (name); // Jack

//    不要忘記使用var關鍵字
//    如果宣告一個變數的時候沒有使用var關鍵字,那麼這個變數將會是一個全域變數! // If you don't declare your local variables with the var keyword, they are part of the global scope

var name = "Michael Jackson";

function showCelebrityName () {function showCelebrityName (    console.log (name);
}

function showOrdinaryPersonName () {   
    name = "Johnny Evers";
 showCelebrityName (); // Michael Jackson

// name is not a local variable, it simply changes the global name variable
showOrdinaryPersonName (); // Johnny Evers
showOrdinaryPersonName (); // Johnny Evers
/🎜>// global variable is now Johnny Evers, not the celebrity name anymore
showCelebrityName (); // Johnny Evers

// The solution is to declare your local variable with the var keys

    var name = "Johnny Evers"; // Now name is always a local variable and it will not overwrite the global variable
    console.log (name);    console.log (name);//如果在全域作用域中什麼的變數在局部作用域中再次聲明,那麼在局部作用域中呼叫這個變數時,優先呼叫局部作用域中聲明的變數:
var name = "Paul";

function users () {
    // Here, the name variable is local and it takes precedence over the same name variable in the global and it takes precedence over the same name variable in the global scope
"Jack";

// The search for name starts right here inside the function before it attempts to look outside the function in the global scope
console.log (name);
}

users (); // Jack





全域變數

所有在函數外宣告的變數都處於全域作用域。在瀏覽器環境中,這個全域作用域就是我們的Window物件(或整個HTML文件)。

每一個在函數外部宣告或定義的變數都是全域對象,所以這個變數可以在任何地方被使用,例如:


複製程式碼

程式碼如下:

// name and sex is not in uncis not not >var myName = "zhou";var sex = "male";//他們都處在window物件console.log(window.myName); //paul
console.log('sex' in window); //true



如果一個變數第一次初始化/宣告的時候沒有使用var關鍵字,那麼他就會自動加入全域作用域。



複製程式碼


程式碼如下:


function showAge(){
  //age初始化時沒有使用var關鍵字,所以它是全域變數
  age = 20;
  console.log(age);
}

showAge();  //20
console.log(age); //因為age是全域變量,所以這裡輸出的也是20

setTimeout中的函數是在全域作用域中執行的

setTimeout中的函數所處在於全域作用域中,所以函數中使用this關鍵字時,這個this關鍵字指向的是全域物件(Window):

複製程式碼 代碼如下:

var Value1 = 200;


var Value1 = 200;
;
var myObj = {
  Value1 : 10,
  Value2 : 1,

  caleculated. this.Value1 * this.Value2);
    }, 1000);
  }
}
myObj.caleculatedIt(); //4000


為了避免對全域作用域的污染, 所以一般情況下我們盡可能少的宣告全域變數。 
變數提升(Variable Hoisting)

所以的變數宣告都會提升到函數的開頭(如果這個變數在這個函數裡面)或是全域作用域的開頭(如果這個變數是全域變數)。我們來看一個例子:

程式碼如下:


function showconn () {


function showg () {


function show "First Name: " name);
var name = "Ford";
console.log ("Last Name: " name);
}

showName ();
// First Name: undefined
// Last Name: Ford

// The reason undefined prints first is because the local variable name was hoisted to the top of the function
/ heich is this local variable that get calls the first time.
// This is how the code is actually processed by the JavaScript engine:

function showName () {
>   name; hoisted (note that is undefined at this point, since the assignment happens below)
console.log ("First Name: " name); // First Name: undefined

name = "Ford"; / / name is assigned a value

// now name is Ford

console.log ("Last Name: " name); // Last Name: Ford}


複製程式碼


程式碼如下:


// Both the variable and the function name the functionvar myName;?
function myName () {console.log ("Rich");

}

// The function declaration overrides the variable name

// The function declaration overrides the variable name

consoles. log(typeof myName); // function


複製程式碼


程式碼如下:


// But in this example, the v.able signment function declaration
var myName = "Richard"; // This is the variable assignment (initialization) that overrides the function declaration.

function myName () {

console.log"🎜>function myName () {console.log"🎜>function myName () {

console.log" ;

}console.log(typeof myName); // string 最後一點, 在嚴格模式下,如果沒有先宣告變數就給變數賦值將會報錯!
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
node.js流帶打字稿node.js流帶打字稿Apr 30, 2025 am 08:22 AM

Node.js擅長於高效I/O,這在很大程度上要歸功於流。 流媒體匯總處理數據,避免內存過載 - 大型文件,網絡任務和實時應用程序的理想。將流與打字稿的類型安全結合起來創建POWE

Python vs. JavaScript:性能和效率注意事項Python vs. JavaScript:性能和效率注意事項Apr 30, 2025 am 12:08 AM

Python和JavaScript在性能和效率方面的差異主要體現在:1)Python作為解釋型語言,運行速度較慢,但開發效率高,適合快速原型開發;2)JavaScript在瀏覽器中受限於單線程,但在Node.js中可利用多線程和異步I/O提升性能,兩者在實際項目中各有優勢。

JavaScript的起源:探索其實施語言JavaScript的起源:探索其實施語言Apr 29, 2025 am 12:51 AM

JavaScript起源於1995年,由布蘭登·艾克創造,實現語言為C語言。 1.C語言為JavaScript提供了高性能和系統級編程能力。 2.JavaScript的內存管理和性能優化依賴於C語言。 3.C語言的跨平台特性幫助JavaScript在不同操作系統上高效運行。

幕後:什麼語言能力JavaScript?幕後:什麼語言能力JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript在瀏覽器和Node.js環境中運行,依賴JavaScript引擎解析和執行代碼。 1)解析階段生成抽象語法樹(AST);2)編譯階段將AST轉換為字節碼或機器碼;3)執行階段執行編譯後的代碼。

Python和JavaScript的未來:趨勢和預測Python和JavaScript的未來:趨勢和預測Apr 27, 2025 am 12:21 AM

Python和JavaScript的未來趨勢包括:1.Python將鞏固在科學計算和AI領域的地位,2.JavaScript將推動Web技術發展,3.跨平台開發將成為熱門,4.性能優化將是重點。兩者都將繼續在各自領域擴展應用場景,並在性能上有更多突破。

Python vs. JavaScript:開發環境和工具Python vs. JavaScript:開發環境和工具Apr 26, 2025 am 12:09 AM

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

JavaScript是用C編寫的嗎?檢查證據JavaScript是用C編寫的嗎?檢查證據Apr 25, 2025 am 12:15 AM

是的,JavaScript的引擎核心是用C語言編寫的。 1)C語言提供了高效性能和底層控制,適合JavaScript引擎的開發。 2)以V8引擎為例,其核心用C 編寫,結合了C的效率和麵向對象特性。 3)JavaScript引擎的工作原理包括解析、編譯和執行,C語言在這些過程中發揮關鍵作用。

JavaScript的角色:使網絡交互和動態JavaScript的角色:使網絡交互和動態Apr 24, 2025 am 12:12 AM

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境