简体   繁体   English

JavaScript全局和局部范围

[英]JavaScript Global and Local Scope

I have a question regarding scoping in JavaScript. 我有一个关于JavaScript范围界定的问题。

If I have this code: 如果我有此代码:

var v = 10;
function fun() {
  v = 20;
  if (v > 10) {
    var v = 0;
  }
}
fun();

Why is v still 10, after executing fun(); 为什么在执行fun()之后v仍然是10? ? I mean isnt v = 20; 我的意思是isnt v = 20; global? 全球? So doesnt it change the value of v from 10 = 20? 那么它不会将v的值从10 = 20改变吗? I am little bit confused, I already tried reading about JavaScript scoping but didnt help me understanding why it is still 10... 我有点困惑,我已经尝试阅读有关JavaScript作用域的信息,但并没有帮助我理解为什么它仍然是10 ...

I would be very gratefull if someone could give me a an explantion... :) 如果有人能给我一个移植物,我将不胜感激... :)

This is because of the line var v = 0; 这是因为行var v = 0; by doing this you have create a local variable in the function called v so when you say v=20 you are referring to the local v not the global v. 通过执行此操作,您已在名为v的函数中创建了局部变量,因此当您说v =​​ 20时,是指局部v而不是全局v。

To prove this I created this snippet to show it is the var that creates this behavior. 为了证明这一点,我创建了此代码片段,以表明正是var导致了此行为。 The log function in the snippet is just there so you can view the output in the DOM. 代码段中的日志功能就在那里,因此您可以在DOM中查看输出。

 var v = 10; function fun() { v = 20; if (v > 10) { var v = 0; } } function bar() { v = 20; if (v > 10) { v = 0; } } log("Before fun:",v); fun(); log("After fun:",v); bar(); log("After bar:",v); function log (){ document.getElementById("log").innerHTML += Array.prototype.slice.call(arguments).join(' ') + '<br>'; } 
 <div id="log"></div> 

The best way I have found to visualize this process is the following. 我发现可视化此过程的最佳方法如下。

var v = 10;
function fun() {
  v = 20;
  if (v > 10) {
    var v = 0;
  }
}
fun();

I convert this into the following in my mind which is the process of hoisting. 我认为这是提升过程。

var v = 10;
function fun() {
  var v;
  v = 20;
  if (v > 10) {
    v = 0;
  }
}
fun();

With this new code it is clear that v = 20 refers to the local v not the global v. 通过此新代码,很明显v = 20是指局部v而不是全局v。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM