参见英文答案 >
Using the variable “name” doesn’t work with a JS object3个
> Do let statements create properties on the global object?4个
特定
> Do let statements create properties on the global object?4个
特定
let obj = {name: 1}; console.log(typeof obj.name,obj.name); // `"number"`,`1`
在对象解析赋值时使用var时,为什么名称标识符被转换为字符串?
let obj = {name: 1}; var {name} = obj; console.log(name,typeof name); // `1` `string`
但是不使用let或const?
let obj = {name: 1}; let {name} = obj; console.log(name,typeof name);
我们可以通过定义不同的标识符来避免这种意外结果
let obj = {name: 1}; var {name:_name} = obj; console.log(_name,typeof _name);
虽然好奇的是var在浏览器环境中返回不同于let或const的名称标识符的结果?
解决方法
此行为由执行代码的范围定义.
name是指window.name
属性,当被指定为window.name = 1时,该描述符有一个setter to convert it to string:
A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)
在全局范围内执行时,var name = …为window.name赋值.而let和const声明了块范围的变量.
在本地范围内执行时,name将在以下两种情况下引用局部变量:
(() => { var obj = {name: 1}; var {name} = obj; console.log(typeof name); // 'number' })();