JS解构getComputedStyle返回值时声明top报标识符已声明错误
问题描述
编写JavaScript代码时,希望通过解构赋值快速获取window.getComputedStyle的返回属性,初始可正常运行的代码如下:
const { width, height, left } = window.getComputedStyle(document.querySelector('canvas')); console.log(width, left, height)
配套HTML代码:
<canvas></canvas>
上述代码运行正常,控制台可正确输出对应属性值。但在解构属性列表中新增top属性后,代码抛出如下错误:
Uncaught SyntaxError: Identifier top has already been declared
报错对应的代码如下:
const { width, height, left, top } = window.getComputedStyle(document.querySelector('canvas')); console.log(width, left, height)
代码中没有提前声明过名为top的标识符,且解构left属性时没有出现同类问题。
问题原因
报错核心原因是浏览器全局作用域默认预置了只读的window.top属性,该属性指向当前窗口层级的最顶层窗口对象,属于浏览器内置的全局标识符,不允许在全局作用域下通过const/let重复声明同名变量。
解构width、height、left时不触发报错,是因为全局作用域下没有预置这些名称的只读绑定,不会触发重复声明的语法校验。
解决方案
可任选以下两种方式修复问题:
- 解构时对
top属性重命名,避开和全局top标识符的命名冲突const { width, height, left, top: topStyle // 将解构得到的top属性重命名为自定义变量名 } = window.getComputedStyle(document.querySelector('canvas')); console.log(width, left, height, topStyle) - 将代码放到独立的块级作用域/函数作用域中执行,避开全局作用域的标识符限制
// 通过立即执行函数创建独立作用域 (() => { const { width, height, left, top } = window.getComputedStyle(document.querySelector('canvas')); console.log(width, left, height, top) })()
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

