在 JavaScript 中,var
声明会在全局对象上创建属性:
var x = 15;
console.log(window.x); // logs 15 in browser
console.log(global.x); // logs 15 in Node.js
ES6 通过let
具有块作用域的声明引入了词法作用域。
let x = 15;
{
let x = 14;
}
console.log(x); // logs 15;
但是,这些声明是否会在全局对象上创建属性?
let x = 15;
// what is this supposed to log in the browser according to ES6?
console.log(window.x); // 15 in Firefox
console.log(global.x); // undefined in Node.js with flag