今天,我遇到一个问题,top
是一个预先存在的全局变量。
const left = 1;
const right = 2;
const top = 3;
const bottom = 4;
console.log(left,right,top,bottom);
结果:
Uncaught SyntaxError: Identifier 'top' has already been declared
我想直到今天我大多数时候都在使用一个叫做top
的变量在函数内部。
我需要担心浏览器添加新的全局变量,这些变量将来会破坏代码吗?直到es6导入,几乎所有浏览器库似乎都使用全局变量,除非它们具有构建步骤。但是,看一下top
示例,似乎浏览器可以随时添加新的无法设置的全局变量,因此应不惜一切代价避免使用它们。我看到诸如HTMLElement
之类的一些变量是可分配的。
console.log(HTMLElement);
HTMLElement = 'foo';
console.log(HTMLElement);
结果:
function HTMLElement() { [native code] }
foo
top
是否有些遗留问题,但是浏览器规格承诺将来不会做更多的事情?就像我无法分配window
const window = 'foo';
console.log(window);
结果:
SyntaxError: Identifier 'window' has already been declared
但是我可以在节点中分配process
Welcome to Node.js v12.6.0.
Type ".help" for more information.
> process
process {
version: 'v12.6.0',versions: {
node: '12.6.0',...
}
> process = 'foo'
'foo'
> process
'foo'
>