Why window or document can't be set to undefin

2020-03-17 04:44发布

This might be a silly question but I haven't found an answer to it. Why can't we do the following?

window = undefined

OR

document = undefined

I know those are globals and are available in browsers but thinking of how JavaScript works, is it not possible? Are those re-evaluated every time we try to access them?

I am also interested in knowing how the window or document objects remain what they are even after setting them to a random value... may be a number or undefined or null.

2条回答
够拽才男人
2楼-- · 2020-03-17 04:56

According to 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.

Meaning window is the context in which all of your scripts are evaluated. If it was writable then the above wouldn't hold and the implementation wouldn't follow the spec, therefore it isn't writable.
For similar reasons you can add properties to document but you can't override it.

You can verify this by looking at the IDL:

[Unforgeable] readonly attribute WindowProxy window;
[Unforgeable] readonly attribute Document document;
查看更多
爷、活的狠高调
3楼-- · 2020-03-17 05:00

window is the context. You cant't do this = something else. document is property of window. It is not writable or configurable.

Object.getOwnPropertyDescriptor( window, 'document' );

output

Object {value: document, 
   writable: false,
   enumerable: true, 
   configurable: false}
查看更多
登录 后发表回答