object.freeze
时间: 2023-12-10 13:03:53 浏览: 84
The `Object.freeze()` method is used to freeze an object. When an object is frozen, the properties of the object cannot be modified, added, or removed. This means that the object becomes immutable, and any attempt to modify it will result in an error. The `Object.freeze()` method returns the same object that was passed to it as an argument.
Example:
```js
const obj = {
name: "John",
age: 30
};
// Freeze the object
Object.freeze(obj);
// Trying to modify the object will result in an error
obj.age = 40; // Throws an error
// Trying to add a new property will also result in an error
obj.gender = "male"; // Throws an error
```
Note that `Object.freeze()` only freezes the top-level properties of an object. If the properties of an object are themselves objects, those nested objects are not automatically frozen. To freeze the nested objects as well, you need to call `Object.freeze()` on each of them separately.
阅读全文