You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法重新赋值window.document属性?

Why Can't I Overwrite window.document in JavaScript?

Great question! Let's unpack why your attempt to reassign window.document doesn't stick, even when inspecting window directly doesn't show an obvious "read-only" marker.

The Hidden Truth: window.document Is an Accessor Property

The reason you don't see a read-only flag when looking at window in the console is that document isn't a standard data property (the kind you'd create with let x = 5). Instead, it's an accessor property managed by getter and setter functions under the hood.

To see its actual configuration, run this code:

console.log(Object.getOwnPropertyDescriptor(window, 'document'));

In nearly all modern browsers, you'll get an object like this:

{
  configurable: false,
  enumerable: true,
  get: ƒ document(), // Built-in getter that returns the document object
  set: undefined     // No setter exists to handle reassignment
}

Since the set property is undefined, there's no way to assign a new value to window.document. When you run window.document = 3, the JavaScript engine checks for a setter, finds none, and silently ignores your assignment—no error is thrown, but the original document object remains intact.

Why Browsers Do This: DOM Standards & Security

This behavior is enforced by the DOM specification, which requires that window.document always returns the current page's document object and cannot be replaced. This is critical for both consistency and security: the document object is the gateway to manipulating the page's content, allowing arbitrary replacement would break core browser functionality and open up potential attack vectors.

Keep in mind that host objects (like those provided by browsers, not native JavaScript objects) often have special behaviors that don't match regular JS objects. Using Object.getOwnPropertyDescriptor() is the reliable way to check the real constraints of these properties.

内容的提问来源于stack exchange,提问作者Artem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:11:24