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

为何冻结document.body对象后仍能修改其属性?

Why can I still modify properties of document.body after calling Object.freeze() on it?

Great question — this is a super common point of confusion with how Object.freeze() works, especially when dealing with DOM objects like document.body. Let's break down exactly what's happening here:

1. Object.freeze() only locks down data properties (not accessor properties)

First, let's clarify the core behavior of Object.freeze():

  • It makes all data properties of an object non-writable, non-configurable, and non-enumerable (if they weren't already). This means you can't change their values, delete them, or redefine their behavior.
  • For accessor properties (properties defined with get and set functions), Object.freeze() only marks the property as non-configurable. You still can't delete the property or convert it to a data property, but you can still call its set function if it exists.

Most properties on document.body (like innerHTML, style, or className) are accessor properties, not data properties. When you assign a value to document.body.innerHTML, you're not directly modifying a value stored on the document.body object — you're calling a setter function that updates the underlying DOM structure. Since Object.freeze() doesn't disable these setter functions, you'll still see the DOM change, giving the illusion that the property was modified.

2. Nested objects aren't automatically frozen

Another key detail: if a property on the frozen object is itself an object (like document.body.style), that nested object isn't frozen unless you explicitly call Object.freeze() on it too. So even after freezing document.body, you could still modify properties on document.body.style (e.g., document.body.style.color = 'red') unless you freeze that style object separately.

3. How this plays out with your code

Let's look at your example code (cleaned up for clarity):

'use strict';
document.body.innerHTML = "Hello#1";
var frozen = Object.freeze(document.body);
document.body.innerHTML = "Hello#2"; // This still works!

Even in strict mode, this assignment doesn't throw an error because we're not modifying a frozen data property — we're invoking the innerHTML setter, which operates outside the scope of the frozen document.body object itself.

Quick note on arrays

As a side point (per your reference): when you freeze an array, its elements (which are data properties mapped to indices) become non-writable. This means you can't change existing elements, add new ones, or remove existing ones — a key difference from how accessor properties on DOM objects behave.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:11:40