Question

code is:

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

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

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top