簡體   English   中英

JavaScript中的變量和函數范圍

[英]variables and function scope in javascript

我有這段代碼

var a = 5;
function woot(){
    console.log(a);
    var a = 6;
    function test(){ console.log(a);}
    test();
  };
woot();

我期望5和6作為輸出,但我有未定義和6。

有什么想法嗎?。

變量聲明被提升到它們出現的范圍的頂部。 您的代碼的解釋如下:

var a; // Outer scope, currently undefined
a = 5; // Outer scope, set to 5

function woot(){ // Function declaration, introduces a new scope
    var a; // Inner scope, currently undefined
    console.log(a); // Refers to inner scope 'a'
    a = 6; // Inner scope, set to 6
    function test(){ console.log(a);} // Refers to inner scope 'a' (now 6)
    test();
  };
woot();

當你聲明函數內部變量,該變量將陰影與已在祖先的范圍被宣布為相同標識符的任何變量。 在您的示例中,您在全局范圍內聲明a 然后,在woot函數的作用域中聲明另一個具有相同標識符的變量。 此變量遮蓋了您在全局范圍內聲明的a

變量聲明( var關鍵字) 懸掛在你的范圍woot功能,使其成為一個局部變量(陰影全局變量a )。 它將初始化為undefined ,並返回該值,直到您為其分配值為止。

在那個時間:

function woot(){
console.log(a);

..the a犯規存在呢! 如果你想使用外a你需要調用它像:

console.log( window.a );

刪除a你已經在功能上,你可以使用,現在放寬,即console.log(a); 它將引用外部的(因為您的函數中已經沒有了)

否則,請使用console.log( window.a ); 區分兩個alphas

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM