[導入]variable's scope in Javascript

          Posted on 2006-03-16 11:19 BlueO2 閱讀(498) 評論(0)  編輯  收藏 所屬分類: AJAX

          See DFlying's finding:
          Yep,No Block Scope concept in JavaScript.Only the global and function Scope.You can use "var" to declare a global variable and use "var" agian to declare a homonymous variable in a function.In the function ,the second one works.But there is no Block scope.
          Check the codes below,it's a demo for "NO BLOCK SCOPE"
          function test(o) {var i = 0; // i is defined throughout functionif (typeof o == "object") {var j = 0; // j is defined everywhere, not just blockfor(var k = 0; k < 10; k++) { // k is defined everywhere, not just loopdocument.write(k);

          }document.write(k); // k is still defined: prints 10}document.write(j); // j is defined, but may not be initialized}

          But,You still need to care javascript's FUNCTION SCOPE.Also see code snippet:
          var scope = "global";

          function f( ) {alert(scope); // Displays "undefined", not "global"var scope = "local"; // Variable initialized here, but defined everywherealert(scope); // Displays "local"}f( );
          Right,thought you alert(scope) first and then define a new functin scope variable scope.However,once you define a function scope vriable,it will hide the global variable in the function body,whatever the definition order.



          文章來源:http://blueoxygen.dflying.net/3/archive/68_variables_scope_in_javascript.html

          posts - 29, comments - 3, trackbacks - 0, articles - 0

          Copyright © BlueO2

          主站蜘蛛池模板: 南康市| 永济市| 阿拉善左旗| 福贡县| 武鸣县| 阿图什市| 星子县| 泊头市| 两当县| 武隆县| 天长市| 湘潭县| 汤阴县| 江永县| 马鞍山市| 平利县| 泽库县| 邢台市| 宝鸡市| 开阳县| 微山县| 开鲁县| 奇台县| 鹤峰县| 晋城| 拉萨市| 綦江县| 伊金霍洛旗| 镇坪县| 无锡市| 华蓥市| 科技| 蕉岭县| 绥中县| 建瓯市| 常德市| 南充市| 禄丰县| 南木林县| 高雄市| 西贡区|