artwl
artwl

Reputation: 3582

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?

Upvotes: 1

Views: 72

Answers (3)

David G
David G

Reputation: 96810

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

Upvotes: 2

Tadeck
Tadeck

Reputation: 137320

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

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

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

Upvotes: 4

Related Questions