Javascript中的变量范围(提升) [英] Scope of variables (Hoisting) in Javascript
问题描述
var全局变量= false;
函数test(){
global = true;
返回false;
函数global(){}
}
console.log(global); //说假(正如所料)
test();
console.log(global);如果我们假设函数在顶部被悬挂起来,那么这个函数在顶部被悬挂起来,以及var变量,让我们试试这个。 var foo = 1;
函数bar(){
return foo;
foo = 10;
函数foo(){}
var foo = 11;
}
bar();
console.log(foo); //说1(但应该是11)为什么1这次?
这是 JSBin Demo 和 function global(){} $ c $> c>从 test()
,然后运行正常。有人可以帮我理解为什么会发生这种情况吗?
并且函数声明语句被悬挂到其封闭范围的顶部。
因此,函数中的函数global(){}
会创建一个本地全球
名称。
分配给全球
函数绑定到这个本地名称。下面介绍如何使用提升来重写它,以了解编译器如何看待它:
function test(){
var global = function(){}; //悬挂; 'global'now local
global = true;
返回false;
}
One of my friends was taking an online quiz and he asked me this question which I could not answer.
var global = false;
function test() {
global = true;
return false;
function global() {}
}
console.log(global); // says false (As expected)
test();
console.log(global); // says false (Unexpected: should be true)
If we assume that functions are hoisted at the top along with var variables, let's try this one.
var foo = 1;
function bar() {
return foo;
foo = 10;
function foo() {}
var foo = 11;
}
bar();
console.log(foo); //says 1 (But should be 11) Why 1 this time ??
Here is a JSBin Demo and JSBIN Demo2 to play with.
PS: If we remove function global() {}
from test()
, then it runs fine. Can somebody help me understand why is this happening ?
解决方案 var
statements and function declaration statements are "hoisted" to the top of their enclosing scope.
Therefore, the function global(){}
in your function creates a local global
name.
Assigning to global
inside your functions binds to this local name. Here's how you can "rewrite" it using hoisting to understand how the compiler sees it:
function test() {
var global = function() {}; // hoisted; 'global' now local
global = true;
return false;
}
这篇关于Javascript中的变量范围(提升)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!