是否存在不需要花括号来创建可以声明局部变量的新作用域的情况?不管我怎么想,它确实有花括号:例如 block 、条件、循环、try/catch 等。并且,例如没有 block 体的箭头函数似乎不会创建新的作用域。
最佳答案
带有 let
的 for
循环创建一个作用域:
let x = "hello world";
for (let x = 0; x < 10; x++) console.log(x); // numbers ...
console.log(x); // "hello world"
该代码中没有 { }
。
箭头函数确实创建一个新的作用域,但它们不会创建新的this
绑定(bind)。
let x = "hello world";
let y = () => { let x = "new scope"; console.log(x); };
y(); // "new scope"
console.log(x): // "hello world"
关于javascript - 词法作用域只能在大括号之间创建吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56672307/