官术网_书友最值得收藏!

Scope of Variables

I t is important to note, especially if you have come to JavaScript from another language, that variables in JavaScript are not defined in a block scope, but in a function scope. This means that if a variable is defined inside a function, it's not visible outside of the function. However, a variable defined inside an if or a for code block is visible outside the code block. The term "global variables" describes variables you define outside of any function, as opposed to "local variables" which are defined inside a function. The code inside a function has access to all global variables as well as to its own local variables.

In the next example:

  • The function f() has access to the variable global
  • Outside of the function f(), the variable local doesn't exist
var global = 1;
function f() {
  var local = 2;
  global++;
  return global;
}
>>> f();

2

>>> f();

3

>>> local

local is not defined

It is also important to note that if you don't use var to declare a variable, this variable is automatically assigned global scope. Let's see an example:

Scope of Variables

What happened? The function f() contains the variable local. Before calling the function, the variable doesn't exist. When you call the function for the first time, the variable local is created with a global scope. FThen if you access local outside the function, it's available.

Tip

B est Practice Tips

  • Minimize the number of global variables. Imagine two people working on two different functions in the same script and they both decide to use the same name for their global variable. This could easily lead to unexpected results and hard-to-find bugs.
  • Always declare your variables with the var statement.

Here's an interesting example that shows an important aspect of the local versus global scoping.

var a = 123;
function f() { 
  alert(a);
  var a = 1;
  alert(a); 
} 
f(); 

You might expect that the first alert() will display 123 (the value of the global variable a) and the second will display 1 (the local a). This is not the case. The first alert will show "undefined". This is because inside the function the local scope is more important than the global scope. So a local variable overwrites any global variable with the same name. At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space.

主站蜘蛛池模板: 阿坝县| 景洪市| 林口县| 淮南市| 炉霍县| 台南市| 威海市| 遵义县| 定西市| 理塘县| 德庆县| 德庆县| 通河县| 长岭县| 郯城县| 南昌市| 舒城县| 太仆寺旗| 农安县| 汾西县| 营口市| 来凤县| 五河县| 伊金霍洛旗| 平谷区| 巫溪县| 如皋市| 宁武县| 洛南县| 永安市| 纳雍县| 庄河市| 清镇市| 盘山县| 栾川县| 江川县| 寿光市| 革吉县| 西乌珠穆沁旗| 本溪市| 定安县|