JavaScript policy on global variables / the global namespace

二次信任 提交于 2020-04-10 03:03:56

问题


Today I ran into an issue that top is a pre-existing global variable.

const left = 1;
const right = 2;
const top = 3;
const bottom = 4;
console.log(left, right, top, bottom);

result:

Uncaught SyntaxError: Identifier 'top' has already been declared

I think I've just been lucky until today that most of the time my usage of a variable called top was inside a function.

How much do I need to worry about browsers adding new global variables that will break code in the future? It seems like until es6 import pretty much all browser libraries used global variables unless they had a build step. But, looking at the top example it seems like browser could add new unsettable global variables at anytime and therefore they should be avoided at all costs. I see some variables things like HTMLElement are assignable.

console.log(HTMLElement);
HTMLElement = 'foo';
console.log(HTMLElement);

result:

function HTMLElement() { [native code] }
foo

Is top some legacy thing but browser specs promise not to do more of that in the future? Like I can't assign window

const window = 'foo';
console.log(window);

result:

SyntaxError: Identifier 'window' has already been declared

but I can assign process in node

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'
> 

来源:https://stackoverflow.com/questions/59285488/javascript-policy-on-global-variables-the-global-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!