Object.seal 函数
阻止修改现有属性的特性,并阻止添加新属性。
语法
Object.seal(object)
参数
object
必要参数。在其上锁定特性的对象。
返回值
传递给函数的对象。
异常
如果object参数不是对象,则将引发TypeError异常。
备注
Object.seal函数执行以下两项操作:
- 使对象不可扩展,这样便无法向其添加新属性。
- 为对象的所有属性将configurable特性设置为false。
在configurable特性为false时,无法更改属性的特性且无法删除属性。在configurable为false且writable为true时,可以更改value和writable特性。
Object.seal函数不更改writable特性。
欲进一步了解如何设置属性的特性,请参阅Object.defineProperty 函数。若要取得属性的特性,可使用Object.getOwnPropertyDescriptor 函数。
相关函数
以下相关函数可阻止修改对象的特性。
函数 | 对象已设置为不可扩展的 | 为每个属性将configurable设置为false | 为每个属性将writable设置为false |
---|---|---|---|
Object.preventExtensions | Yes | No | No |
Object.seal | Yes | Yes | No |
Object.freeze | Yes | Yes | Yes |
如果满足表中标记的所有条件,则以下函数返回true。
函数 | 函数 | 对象是否可扩展 | 为所有属性将configurable设置为false | 为所有数据属性将writable设置为false |
---|---|---|---|---|
Object.isExtensible | Yes | No | No | |
Object.isSealed | No | Yes | No | |
Object.isFrozen | No | Yes | Yes |
示例
下面的示例演示了Object.seal
函数的用法。
// Create an object that has two properties. 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
必备条件
在以下文档模式中受支持:Internet Explorer 9标准模式、Internet Explorer 10标准模式、Internet Explorer 11标准模式。应用商店应用(Windows 8和Windows Phone 8.1)中也受支持。请参阅版本信息。
在以下文档模式中不受支持:怪异模式、Internet Explorer 6 标准模式、Internet Explorer 7 标准模式、Internet Explorer 8 标准模式。