Object.seal 函数 (JavaScript)
阻止修改现有属性的特性,并阻止添加新属性。
语法
JavaScript
Object.seal(object)
参数
object
必需。在其上锁定特性的对象。
返回值
传递给函数的对象。
异常
如果 object 参数不是对象,则将引发 TypeError 异常。
Exception | Condition |
---|
备注
Object.seal 函数执行以下两项操作:
-
使对象不可扩展,这样便无法向其添加新属性。
-
为对象的所有属性将 configurable 特性设置为 false。
在 configurable 特性为 false 时,无法更改属性的特性且无法删除属性。在 configurable 为 false 且 writable 为 true 时,可以更改 value 和 writable 特性。
Object.seal 函数不更改 writable 特性。
var obj = { pasta: "spaghetti", length: 10 }; // Seal the object. Object.seal(obj); document.write(Object.isSealed(obj)); document.write("<br/>"); // Try to add a new property, and then verify that it is not added. obj.newProp = 50; document.write(obj.newProp); document.write("<br/>"); // Try to delete a property, and then verify that it is still present. delete obj.length; document.write(obj.length); // Output: // true // undefined // 10
Object.freeze 函数 (JavaScript)
阻止修改现有属性的特性和值,并阻止添加新属性。
语法
JavaScript
Object.freeze(object)
参数
object
必需。在其上锁定特性的对象。
返回值
传递给函数的对象。
var obj = { pasta: "spaghetti", length: 10 }; // Freeze the object. Object.freeze(obj); // Try to add a new property, and then verify that it is not added. obj.newProp = 50; document.write(obj.newProp); document.write("<br/>"); // Try to delete a property, and then verify that it is still present. delete obj.length; document.write(obj.length); document.write("<br/>"); // Try to change a property value, and then verify that it is not changed. obj.pasta = "linguini"; document.write(obj.pasta); // Output: // undefined // 10 // spaghetti