1

code is:

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

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

artwl
  • 3,502
  • 6
  • 38
  • 53
  • 2
    with is not a function, so it doesn't introduce a new variable scope. it just changes what `this` refers to. – ronalchn Sep 03 '12 at 01:33

3 Answers3

4

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

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

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
Community
  • 1
  • 1
Tadeck
  • 132,510
  • 28
  • 152
  • 198
2

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
David G
  • 94,763
  • 41
  • 167
  • 253