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

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.

主站蜘蛛池模板: 广丰县| 门源| 西藏| 晋中市| 运城市| 普兰店市| 上犹县| 彰化县| 盐边县| 梁河县| 宣化县| 岢岚县| 商都县| 北川| 勃利县| 恩施市| 通化县| 南丰县| 民丰县| 长丰县| 曲靖市| 泰来县| 沁源县| 绥棱县| 武宁县| 兴国县| 微山县| 神农架林区| 龙山县| 卢氏县| 虞城县| 胶南市| 河南省| 新源县| 城市| 福建省| 互助| 榆中县| 富川| 丽江市| 图木舒克市|