The problem: global read-only properties
First, note that this problem exists in a Web environment, i.e. in a browser.
Other JS environments may not have this problem.
var closed = 0;
in the global scope doesn’t create a binding that refers to a number and remains being the boolean false
.
The reason for this is that closed
refers to window.closed
in this circumstance; it’s always a boolean, and redefining it produces a linter warning like “Redefinition of closed
”.
This read-only property indicates whether the referenced window is closed or not.
Variables that behave like this can be found in these lists:
These are all the interfaces that globalThis
can be an instance of in Web content scripts.
Run the snippet to get a full list of variable names that you can’t safely use in the global scope:
const props = Object.entries(Object.getOwnPropertyDescriptors(globalThis)),
undesirable = {
set: (desc) => desc,
configurable: (desc) => !desc,
writable: (desc) => !desc
};
Array.from(document.querySelectorAll("[id]"))
.forEach((span) => span.innerHTML = props
.filter(([prop, {[span.id]: desc}]) => undesirable[span.id](desc))
.map(([prop]) => `<code>${prop}</code>`)
.join(", "))
code{
background: #eee;
padding: 1px 3px;
}
<p>Properties that have a setter which may change the type or invoke some function, when a value is set to it:</p>
<span id="set"></span>
<hr/>
<p>Properties that are not configurable:</p>
<span id="configurable"></span>
<hr/>
<p>Properties that are read-only:</p>
<span id="writable"></span>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…