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

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.

主站蜘蛛池模板: 天门市| 米林县| 河津市| 安国市| 三亚市| 慈溪市| 岳池县| 浦江县| 勐海县| 建瓯市| 渝北区| 故城县| 章丘市| 离岛区| 海伦市| 广汉市| 运城市| 海安县| 枝江市| 石阡县| 化德县| 五常市| 筠连县| 阿坝县| 达州市| 青岛市| 县级市| 翁牛特旗| 明溪县| 临颍县| 霍山县| 广丰县| 平原县| 金坛市| 东乌珠穆沁旗| 分宜县| 淮阳县| 麻城市| 宁乡县| 沭阳县| 海宁市|