了解设定范围
问题描述:
我对代码的假设是第二个let x
上面的代码位于时间死区。因此不应该抛出错误。了解设定范围
代码
function f(condition, x) {
if (condition) {
let x = 100;
return x;
}
let x = 30; // <---- throw error
return x;
}
f(true, 1);
答
那么这里的问题是,你重新声明同一变量x
两次在同一function
,所以变量x
将被吊起。
if (condition) {
//This x declaration is fine as it wasn't preceded with any others declaration inside the same block scope
let x = 100;
return x;
}
//Now this second x declaration will cause the hoisting problem
let x = 30; // <---- throw error
这里第二let x = 30;
声明冲顶您function
范围x
变量。所以得出的结论是,你不能在同一个范围内多次声明同一个变量。
有关在Javascript varaible提升进一步的阅读,您可以检查:
答
问题似乎是与X已经是具有相同的范围,因为外X一个函数参数。如果我更改功能参数x与y,代码工作正常。
代码
function f(condition, y) {
if (condition) {
let x = 100;
return x;
}
let x = 30; // <---- doesnt throw error
return x;
}
f(true, 1);
'let'是 “块作用域” - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/发言/让 –
我知道让是块范围 – aWebDeveloper
阅读关于在Javascript中提升,所以你可以了解哪些代码的例子失败。 – Dez