本文介绍了奇怪的javascript范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var c = 1;
function myFunction(){
c = 2;
var c = 4;
console.log(c);
}
console.log(c);
myFunction();
console.log(c);
为什么最后一个console.log吐出1?以下是我的大脑应该如何工作:
Why is the last console.log spitting out 1? Here is how it is supposed to work in my brain:
var c = 1; // create global variable called 'c'
function myFunction(){
c = 2; // assign value of global 'c' to 2
var c = 4; // create a new variable called 'c' which has a new address in memory (right?) with a value of 4
console.log(c); // log the newly created 'c' variable (which has the value of 4)
}
console.log(c); //log the global c
myFunction(); //log the internal c
console.log(c); //log the updated global c
推荐答案
在范围内您的console.log运行时,只存在全局变量。函数永远不会触及全局变量。
In the scope where your console.log runs, only the global variable exists. And the function never touches the global variable.
详细信息:
var c = 1; // create global variable called 'c'
function myFunction(){
// the global is unavailable here, as you declared a local c.
// Its declaration is hoisted to the top of the function, so
// c exists here, and its value is undefined.
c = 2; // assign value of local 'c' to 2
var c = 4; // change local c to 4
console.log(c); // log local c (4)
}
console.log(c); //log the global c
myFunction(); //log the internal c
console.log(c); //log the global c (which never changed)
由于上面提到的提升,你的功能表现如下好像代码是:
Due to the hoisting mentioned above, your function behaves as if the code was:
function myFunction(){
var c; // declares a local c that shadows the global one
c = 2;
c = 4;
console.log(c);
}
关于提升的一些参考
- 的例子中
- MDN page for the
var
statement - MDN scope cheatsheet
- How are javascript variables "hoisted" in these examples from MDN
- Javascript hoisting explained
- JavaScript Scoping and Hoisting
Some references about hoisting
这篇关于奇怪的javascript范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!