簡體   English   中英

為什么局部作用域不引用全局變量?

[英]Why a local scope doesn't refer on a global variable?

我在本地范圍有問題。 第二個console.log不顯示“ a”值,但是顯示未定義。 為什么這樣?

"use strict"

console.log(a); //undefined 
var a = "a";
function b(){
  console.log(a); // why is undefined here? 
  var a = "a1";
  console.log(a); // here is "a1"
}
b();

JS將像這樣處理您的代碼:

"use strict"

var a; // undefined 
console.log(a); //undefined 

a = "a";

function b(){
  var a; // undefined

  console.log(a); // all is clear, LOCAL variable a is undefined. 

  a = "a1";
  console.log(a); // here is "a1"
}

b();

在此處閱讀有關吊裝的更多信息。

您也可以閱讀有關函數聲明提升的信息 ,這也是JavaScript基礎的重要組成部分。

面向對象的JavaScript,第二版:當您的JavaScript程序執行進入一個新函數時,該函數中任何位置聲明的所有變量都將移動(或提升或提升)到該函數的頂部。 這是要記住的重要概念。 此外,僅懸掛聲明,這意味着僅將變量的存在移到頂部。 任何作業都將留在原處。 在前面的示例中,局部變量a的聲明被提升到頂部。

var a = 123;

function f() {

    var a; // same as: var a = undefined;

    alert(a); // undefined

    a = 1;

    alert(a); // 1
}

提升是JavaScript將聲明移到頂部的默認行為。 您的函數范圍中有a變量。 這是執行時的樣子:

"use strict"

console.log(a); //undefined 
var a = "a";
function b(){
  var a;
  console.log(a); // Undefined because a is not set
  a = "a1";
  console.log(a); // here is "a1"
}
b();

因為您在函數b中定義了另一個變量a,所以它像這樣:

function b() {
  var a;
  console.log(a);
  a = "a1";
  console.log(a);
}

暫無
暫無

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

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