![](/img/trans.png)
[英]Groovy:Apparent variable 'classVar' was found in a static scope but doesn't refer to a local variable, static field or class
[英]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();
面向對象的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.