« 上一篇 | 下一篇»

variable's scope in Javascript

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.


(0) 评论    (44) 引用   

Total 0 Comments on "variable's scope in Javascript"

发表评论

称呼 (required)

标题

个人主页(可选)

邮箱地址(可选)

Auth Image