问题
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