`

JavaScript学习(二)

阅读更多

1.var声明的变量是永久性的,不能用delete运算符删除
2.使用var多次声明一个变量是合法的,不会造成任何错误,只不过是重新赋值而已;如果尝试给一个未用var声明的变量赋值,JavaScript会隐式声明该变量,隐式声明的变量会被创建为全局变量。
3.偷个懒,贴断代码:

var scope = "global";         // Declare a global variable
function checkscope( ) {
    var scope = "local";      // Declare a local variable with the same name
    document.write(scope);    // Use the local variable, not the global one
}
checkscope( );                 // Prints "local"

 

如果不使用var来定义变量,看看下面代码的执行结果吧,想不到吧,呵呵

scope = "global";             // Declare a global variable, even without var
function checkscope( ) {
    scope = "local";          // Oops! We just changed the global variable
    document.write(scope);    // Uses the global variable
    myscope = "local";        // This implicitly declares a new global variable
    document.write(myscope);  // Uses the new global variable
}
checkscope( );                 // Prints "locallocal"
document.write(scope);        // This prints "local"
document.write(myscope);      // This prints "local"

 

4.JavaScript变量没有块级作用域

 

 

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( );
 

JavaScript解析器在加载函数时候,总是先把所有var定义的变量声明,然后才会给赋值初始化,这段代码其实相当于:

 

 

function f( ) {
    var scope;       // Local variable is declared at the start of the function
    alert(scope);    // It exists here, but still has "undefined" value
    scope = "local"; // Now we initialize it and give it a value
    alert(scope);    // And here it has a value
}
 

所以,还是建议大家在函数的开头把所有变量声明.

 

5.作为属性的变量

 

两点:<1>全局变量是全局对象的属性

         <2>局部变量是调用对象的属性,每个函数都有自己的调用对象。

         <3>JavaScript允许有多个全局执行环境,这就是框架frame运行的原理;每个框架或者窗口中的JS代码都运行在自己的执行环境中,具有自己的全局变量,但是它们又是有关联的,即:可以用parent.frames[0].x方式来引用另一个框架中的变量。

 

6.作用域链

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics