为什么 window 或 document 不能设置为 undefined 或 null?

Why window or document can't be set to undefined or null?

这可能是一个愚蠢的问题,但我还没有找到答案。为什么我们不能做到以下几点?

window = undefined

document = undefined

我知道这些是全局变量并且可以在浏览器中使用,但是想想 JavaScript 是如何工作的,这不可能吗?每次我们尝试访问它们时都会重新评估它们吗?

我也很想知道 windowdocument 对象如何在将它们设置为随机值后保持原样...可能是 numberundefinednull.

根据the standard

The window attribute must return the Window object's browsing context's WindowProxy object. The document attribute must return the Window object's newest Document object.

含义 window 是评估所有脚本的上下文。如果它是可写的,那么上面的内容将不成立并且实现不会遵循规范,因此它是不可写的。
出于类似的原因,您可以向 document 添加属性,但不能覆盖它。

您可以通过查看 IDL 来验证这一点:

[Unforgeable] readonly attribute WindowProxy window;
[Unforgeable] readonly attribute Document document;

window 是上下文。你不能做 this = something 其他。 document 是 window 的 属性。它不可写或不可配置。

Object.getOwnPropertyDescriptor( window, 'document' );

输出

Object {value: document, 
   writable: false,
   enumerable: true, 
   configurable: false}