简体   繁体   中英

Why declare variables in with outside access to?

code is:

with(location)
    {
        var url=href+"aaa";    
    }
alert(url);

the variable url declare in with ,but it can access outside with,why?

Because var url; is hoisted to the top of the function block. JavaScript doesn't have block-level scoping, only closure-level (functions).

See this answer: https://stackoverflow.com/a/185283/548696

The problem is that variables defined within this block are nit scoped to this block (only the object you will enclose after with is).

To achieve block-level scoping, do something like that:

with({"url": href+"aaa"}) {
    // url is available here    
}
alert(url); // but not here

or rather use let statement , as with is considered harmful:

let (url = href + "aaa"){
    // url available here
}
// but not here

In JavaScript, there is no block-level scoping; only function-level scoping. Take these two examples:

if (true) {
    var a = 5;
}

alert(a); // 5

// ...

function foo() {
    var a = 5;
}

foo();

alert(a); // ReferenceError: a is not defined

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