简体   繁体   中英

Why is the variable inside this function global?

I thought any variable defined in a function would be local but I can easily access variable 'e' outside of its function.

function change() {
 var d = 6; 
  e = 7;
}

change();
alert(e); //> alerts 7

Because new variables will enter the global scope by default. var prevents this from happening by constraining a variable's existence to be within the current scope.

因为它是在没有var声明的情况下变成全局window对象的一部分。

你没有明确地声明它,所以它占据了全球范围。

Thats because e is global by default, using var make a scope varible. You can read more about this in Javascript Garden Scope and Namespaces

I am guessing that you are going under this assumption that

JSLint expects that a var will be declared only once, and that it will be declared before it is used.

Problem with your code is you are using one var, but your second line has no var in front of it. That is pushing that varaible e into the global namespace.

Why is it happening? You used a semicolon instead of a comma in the variable declaration.

function change() {
 var d = 6, //Change this to a comma 
     e = 7;
}

change();
alert(e); //will produce an error now

It is surprisingly easy to create global variables, here are some other gotchas I've seen.

// :-( antipattern: implied global variable
function sum(x, y) {
    result = x + y; // result is global
    return result;
}

// :-) better
function sum(x, y) {
    var result = x + y; // result is local
    return result;
}

// :-( antipattern: chain assignments as part of a var declaration
function foo() {
    var a = b = 0; // b is global
}

// :-) better
function foo() {
    var a, b;
    a = b = 0; // both local
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM