我有一个局部范围的问题。第二个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();
我有一个局部范围的问题。第二个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,第2版:当你的JavaScript程序执行进入一个新的功能,所有的变量声明 在函数的任何位置被移动(或升高,或悬挂)的 函数的顶部。记住这是一个重要的概念。 此外,只有声明被提升,这意味着只有 变量的存在被移动到顶端。任何任务都保持在原来的位置。 在前面的例子中,局部变量a的声明是 。
var a = 123;
function f() {
var a; // same as: var a = undefined;
alert(a); // undefined
a = 1;
alert(a); // 1
}
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();
阅读更多关于吊装here。
此外,您还可以阅读Function declaration hoisting,这也是JavaScript基础知识的重要组成部分。
提升是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定义的另一个变量,所以它是这样的:
function b() {
var a;
console.log(a);
a = "a1";
console.log(a);
}
删除第二个'var'到_assign_一个值到全局'var a'而不是_redeclare_它。 –
var a函数内部也是一个全球范围..为什么你声明两个.. – nisar
如果你的兄弟和朋友都被命名为“鲍勃”,你需要更具体的与两个车程。 – dandavis