2013-04-14 35 views
3

我聽不太懂JavaScript功能級別範圍,爲C#程序員看起來有線給我,我會嘗試通過代碼來解釋它:很難理解JavaScript函數級別範圍

CODE#1

//Problem 
//if same named variable (as in global scope) is used inside function scope, 
//then variable defined inside function will be used,global one will be shadowed 
var a = 123; 
function func() { 
    alert(a); //returns undefined,why not just return 123 ? 
    //how come js knew that there is variable 'a' will be defined and used in 
    //this function scope ,js is interpreter based ? 
    var a = 1; //a is defined inside function 
    alert(a); //returns 1 
} 
func(); 

CODE#2

//when a variable(inside function) not named as same as the global, 
//then it can be used inside function,and global variable is not shadowed 
var k = 123; 
function func2() { 
    alert(k); //returns 123 ,why not 'undefined' 
    var c = 1; 
    alert(c); //returns 1 
} 
func2(); 

所以我的問題是

  1. CODE#1爲什麼第一次aundefined,爲什麼不它只是返回123?如何 來js知道有變量'a'將被定義和使用在 這個功能範圍內,js是基於解釋器?

  2. in 代碼#2爲什麼不是k是'undefined'?

http://jsfiddle.net/Nu2Vu/

+2

這就是所謂的'hoisting'在'js' http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html – fedosov

+0

BTW hoising是不一樣的功能級別範圍。嘗試例如(在Firefox中)相同,用'let'代替'var'.it做同樣的事情,'let'具有塊級範圍 – user2264587

回答

7

CODE#1

Hoisting原因所有變量d這些問題將被帶到範圍的頂部,但它將任務留在原來的位置。當一個變量的引用首先在當前範圍內查找時,如果它找不到該變量,它將繼續查找範圍鏈,直到找到該變量爲止。 該代碼解釋是這樣的:

var a = 123; // global var named a declared, assigned a value 
function func() { 
    var a; // the declaration of the local var a gets 
     // hoisted to the top of the scope, but the 
     // assignment is left below, so at the point 
     // it is initialized with a value of `undefined` 
    alert(a); // looks for a local var named a, finds it but 
       // it currently has a value of `undefined` 

    a = 1; // now the value is assigned to the local a 
    alert(a); // returns 1 
} 
func(); 

CODE#2

此代碼的行爲確實因爲closure的方式。 閉包的基本定義是JavaScript函數不僅可以訪問在其自己範圍內定義的變量,還可以訪問可用於其父範圍的變量。

var k = 123; // declares and assigns a value to global k 
function func2() { 
    alert(k); // looks for a local var named k, doesn't find it, 
       // looks in its parent scope (the global scope in 
       // this case) finds k, returns its value of 123 
    var c = 1; 
    alert(c); //returns 1 
} 
func2(); 
+0

+1爲簡單直接的解釋.. thnx –