code is:
with(location)
{
var url=href+"aaa";
}
alert(url);
the variable url
declare in with
,but it can access outside with,why?
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