最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

scope - Why does this work in javascript? - Stack Overflow

programmeradmin0浏览0评论

Just now,I saw some code like this:


if(condition){
    var xx='sss';   
}
//do something

if(condition){
    console.info(xx);
}

Now, I just wonder why the second if statement work? How can it access the xx variable since it is a local variable defined in another if statement?

Just now,I saw some code like this:


if(condition){
    var xx='sss';   
}
//do something

if(condition){
    console.info(xx);
}

Now, I just wonder why the second if statement work? How can it access the xx variable since it is a local variable defined in another if statement?

Share Improve this question edited Feb 22, 2012 at 5:23 Mike Samuel 121k30 gold badges227 silver badges254 bronze badges asked Feb 22, 2012 at 5:17 hguserhguser 36.1k55 gold badges173 silver badges302 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 10

var in JavaScript is scoped to the containing execution context (e.g., the whole function's scope, or the whole global scope if the var is at global scope), not the block. JavaScript doesn't (yet) have block scope (ECMAScript6 looks likely to add it, via the new let keyword).

The code you've quoted is exactly equivalent to this:

var xx;   
if(condition){
    xx='sss';   
}
//do something

if(condition){
    console.info(xx);
}

This is covered by Section 10.5 of the specification, which describes what the engine does when entering a new execution context. (It's basically a two-phase process, first setting up all the declarations, and then executing step-by-step code.)

More: Poor misunderstood var

In JavaScript the scope is exacted to the closure (the last enclosing function block, or defaults to the window object). When a variable is declared anywhere within that function block it is hoisted to the top of the scope, so in essence a variable exists as undefined starting at the very top of the scope if it is declared anywhere in the scope.

Think of it like this, when the code begins executing it scans all the instructions for declarations and allocates the symbol name starting immediately.

console.log(x);  // undefined
console.log(y);  // error: Uncaught ReferenceError: y is not defined
var x;

for that matter you can take it to extremes:

console.log(x);  // undefined, not an error

while (false) {
  if (false) {
    var x;
  }
}

even though var x can't possibly be reached, and during execution would be optimized away pletely. the engine will still hoist the variable to the top of the scope

hope this helps -ck

useful link: http://www.youtube./watch?v=taaEzHI9xyY&feature=youtu.be#t=42m57s

var declarations affect the entire scope of the smallest containing function or program. JavaScript is not block scoped.

Crock says:

Variable Declarations

All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may bee implied globals. Implied global variables should never be used.

The var statements should be the first statements in the function body.

It is preferred that each variable be given its own line and ment. They should be listed in alphabetical order.

var currentEntry; // currently selected table entry
var level;        // indentation level
var size;         // size of table

JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.

Use of global variables should be minimized. Implied global variables should never be used.

Note, this is changing with the let statement, and in current JavaScript (EcmaScript 5), the variable name in a catch block is block scoped.

javascript doesn't have block scope, so var xx='sss' is either locally scoped (if your sample code is inside a function) or globally scoped (if your sample code is not contained in a function).

JavaScript is a dynamic language, that isn't always picky about things like variable scoping. So, this "feature" allows you to write the code

if (condition) {
    var xx = 'sss';
} else {
    var xx = 'ttt';
}

// do something

if (condition) {
    console.info(xx);
}

I would remend avoiding this, since it makes your program harder to understanda and reason about.

If you declare a variable using var within a function, the variable is scoped to within that function. An if statement is not a function.

I'm assuming in this case both if statements are within the same function and therefore xx is in scope?

If a variable is declared inside a conditional statement, it is still available anywhere following the declaration in the containing function (or globally if the conditional is not in a function). However, it will equal undefined if the condition evaluates to false, unless the variable is later assigned a value.

If a local variable is referenced globally or in another function, a JavaScript error will occur. Depending on your browser, the error may say the variable "is not defined" or "is undefined". This is different from the variable equaling undefined like mentioned above, because a variable that equals undefined can still be referenced.

发布评论

评论列表(0)

  1. 暂无评论