2013-03-15 181 views
1

在Javascript中,據說使用定義函數時有效的範圍執行函數。當函數被調用時,它與範圍無關。Javascript函數執行範圍

這究竟意味着什麼?有人可以用簡單的例子來解釋嗎?

+1

可能這個鏈接可以幫助http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – rab 2013-03-15 12:31:01

回答

2

以下的輸出是A,因爲foofunction a範圍限定,以便它使用可變data是也是在function a範圍所限定的一個。

它不輸出B,即使功能是,在function b的範圍內調用,其中data = "B"

<div id="output"></div> 
<script> 
    var data = "global"; 

    function a() { 
    var data = "A"; 
    function foo() { 
     document.getElementById('output').innerHTML = data; 
    } 
    return foo; 
    } 

    function b() { 
    var data = "B"; 
    var func = a(); 
    func(); 
    } 

    b(); 
</script> 
0
// Global variables are on every scope chain 
var global = 'global' 

// Function variables are only on a function's scope chain 
function bar() { 
    var fn = 'fn'; 

    // foo called from here where fn is avaialble as a local variable 
    foo(); // undefined 

    return function() { 
    alert(fn) 
    } 
} 


function foo() { 
    // foo can access global because it's on its scope chain 
    alert(global); 

    // Can't access fn because it's on bar's scope chain 
    // so returns undefined 
    alert(typeof fn);  
} 

// the function returned by bar has access to fn 
var f = bar(); // global 

f(); // fn