`

《Javascript -- The Definite Guide》第四章笔记

阅读更多

第四章  变量

 

1.  变量的范围 感觉这个和Java/C++的差别比较大。

 

(1) 首先就是没有block scope,譬如:

function test(o) {
    var i = 0;                      // i is defined throughout function
    if (typeof o == "object") {
        var j = 0;                  // j is defined everywhere, not just block
        for(var k=0; k < 10; k++) { // k is defined everywhere, not just loop
            document.write(k);
        }
        document.write(k);          // k is still defined: prints 10
    }
    document.write(j);              // j is defined, but may not be initialized
}

 

下面这个例子也是同一个原理,不过更加的“不可思议”

var scope = "global";
function f( ) {
    alert(scope);         // Displays "undefined", not "global"
    var scope = "local";  // Variable initialized here, but defined everywhere
    alert(scope);         // Displays "local"
}
f( );

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics