简体   繁体   English

为什么在外部访问中声明变量?

[英]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? 变量url声明中with ,但它可以用,为什么访问之外?

Because var url; 因为var url; is hoisted to the top of the function block. 被提升到功能块的顶部。 JavaScript doesn't have block-level scoping, only closure-level (functions). JavaScript没有块级作用域,只有闭包级(函数)。

See this answer: https://stackoverflow.com/a/185283/548696 看到这个答案: 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). 问题在于,在此块中定义的变量的作用域仅限于此块(只有在with之后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语句 ,因为with被认为是有害的:

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

In JavaScript, there is no block-level scoping; 在JavaScript中,没有块级作用域; 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM