Why does this work in javascript?

2019-05-05 18:48发布

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?

7条回答
孤傲高冷的网名
2楼-- · 2019-05-05 19:04

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 recommend avoiding this, since it makes your program harder to understanda and reason about.

查看更多
\"骚年 ilove
3楼-- · 2019-05-05 19:09

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

查看更多
看我几分像从前
4楼-- · 2019-05-05 19:09

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?

查看更多
Viruses.
5楼-- · 2019-05-05 19:14

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 become 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 comment. 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.

查看更多
该账号已被封号
6楼-- · 2019-05-05 19:21

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 completely. the engine will still hoist the variable to the top of the scope

hope this helps -ck

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

查看更多
来,给爷笑一个
7楼-- · 2019-05-05 19:22

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).

查看更多
登录 后发表回答