JavaScript基础:变量的作用域
JavaScript基础:JS函数中声明的所有变量在整个函数中都是有定义的
中说了一些关于作用域的一些比较难以理解的知识点,
说白了就是javascript中全局变量和局部变量的区别。
我觉的再加入一些关于变量的作用域的知识,这样我们会更深入的理解javascript中变量的作用域及如何的规范应用。
知识扩展:
1. 在JavaScript中,作用域是函数划分的,而不是由(block)划分(比如while,if 和 for语句中间)的。
这样导致的结果是某些代码不好理解(如果你曾经使用过用块划分域的语言)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <script type="text/javascript"> // 定义全局变量 var foo = "test"; // 在 if 块中定义变量 if ( true ) { // 将 foo 置为 'new test' // 注意:重新定义的foo变量现在还在全局作用域中! var foo = "new test"; } // 正如我所说的,foo应该等于“new test”的 alert( foo == "new test" ); // // 创建一个会修改变量 foo 的test新函数 function test() { var foo = "old test"; } // foo只会在函数作用域中起作用 // 调用函数 test(); // 这里确认了 foo 还是等于 'new test' alert( foo == "new test" ); </script> |
2.基于浏览器的JavaScrip有个特性,所有属于全局作用域的变量都是window的变量
1 2 3 4 5 | <script type="text/javascript"> //定义全局变量 var test = "test"; alert(window.test==test); </script> |
3.用var关键字声明变量是一个好习惯,也是最佳实践。
注意:未用var关键字声明的变量,都被视为全局变量(或者叫隐式全局作用域的变量声明)。
1 2 3 4 5 6 7 8 9 10 11 | <script type="text/javascript"> //定义一个有foo值的函数 function test(){ foo="test"; } //调用test函数中定义的foo值 test(); //我们发现foo成了全局变量了 //alert(foo=="test"); alert(window.foo=="test"); </script> |
4.定义局部变量的两种方式。
第一种:你可以在函数体中使用用var关键字显示的声明变量,就是局部变量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <script type="text/javascript"> function test(){ var message="hello!"; alert(message); } </script> <pre lang="javacript" line="1"> <p>第二种:你可以定义函数的时候,将它们声明为参数。</p> <pre lang="javacript" line="1"> <script type="text/javascript"> function test(message){ alert(message); } test("hello!"); </script> |
结束!!!!!
文章评论 已经有 0 条评论!