[英]Why not declare variables outside/at the top of class to avoid using this keyword?
[英]Why declare variables in with outside access to?
代码是:
with(location)
{
var url=href+"aaa";
}
alert(url);
变量url
声明中with
,但它可以用,为什么访问之外?
因为var url;
被提升到功能块的顶部。 JavaScript没有块级作用域,只有闭包级(函数)。
看到这个答案: https : //stackoverflow.com/a/185283/548696
问题在于,在此块中定义的变量的作用域仅限于此块(只有在with
之后with
的对象是is)。
要实现块级作用域,请执行以下操作:
with({"url": href+"aaa"}) {
// url is available here
}
alert(url); // but not here
或者更确切地说使用let
语句 ,因为with
被认为是有害的:
let (url = href + "aaa"){
// url available here
}
// but not here
在JavaScript中,没有块级作用域; 仅功能级作用域。 举两个例子:
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.