在 JavaScript 中使用对象时,控制其可变性对于防止意外更改至关重要。 JavaScript 为此提供了两种方法:Object.freeze() 和 Object.seal()。了解它们的差异和用例是编写健壮代码的关键。
Object.freeze() 方法使对象不可变。这意味着:
Object.freeze(obj);
const obj = { name: "Alice", age: 25 }; Object.freeze(obj); obj.age = 30; // Does nothing (strict mode: throws an error) obj.gender = "female"; // Does nothing (strict mode: throws an error) delete obj.name; // Does nothing (strict mode: throws an error) console.log(obj); // { name: "Alice", age: 25 }
使用 Object.isFrozen() 来确定对象是否被冻结:
console.log(Object.isFrozen(obj)); // true
Object.seal() 方法限制对对象的修改,但不如 Object.freeze() 严格。它允许:
Object.seal(obj);
const obj = { name: "Bob", age: 30 }; Object.seal(obj); obj.age = 35; // Allowed: Existing properties can be modified obj.gender = "male"; // Does nothing (strict mode: throws an error) delete obj.name; // Does nothing (strict mode: throws an error) console.log(obj); // { name: "Bob", age: 35 }
使用 Object.isSealed() 判断对象是否被密封:
Object.freeze(obj);
Feature | Object.freeze() | Object.seal() |
---|---|---|
Add new properties | Not allowed | Not allowed |
Remove existing properties | Not allowed | Not allowed |
Modify existing properties | Not allowed | Allowed |
Reconfigure property descriptors | Not allowed | Not allowed |
Use case | Immutable objects (constants) | Restrict structure but allow value changes |
const obj = { name: "Alice", age: 25 }; Object.freeze(obj); obj.age = 30; // Does nothing (strict mode: throws an error) obj.gender = "female"; // Does nothing (strict mode: throws an error) delete obj.name; // Does nothing (strict mode: throws an error) console.log(obj); // { name: "Alice", age: 25 }
console.log(Object.isFrozen(obj)); // true
防止与对象可变性的混淆:清楚地记录对象被冻结或密封的时间和原因,以避免在团队环境中产生误解。
冻结前密封
以上是掌握 JavaScript 中的 Object.freeze() 和 Object.seal():控制对象可变性的详细内容。更多信息请关注PHP中文网其他相关文章!