Object.seal 函数

阻止修改现有属性的特性,并阻止添加新属性。

语法

Object.seal(object)

参数

object

必要参数。在其上锁定特性的对象。

返回值

传递给函数的对象。

异常

如果object参数不是对象,则将引发TypeError异常。

备注

Object.seal函数执行以下两项操作:

  • 使对象不可扩展,这样便无法向其添加新属性。
  • 为对象的所有属性将configurable特性设置为false

configurable特性为false时,无法更改属性的特性且无法删除属性。在configurablefalsewritabletrue时,可以更改valuewritable特性。

Object.seal函数不更改writable特性。

欲进一步了解如何设置属性的特性,请参阅Object.defineProperty 函数。若要取得属性的特性,可使用Object.getOwnPropertyDescriptor 函数

相关函数

以下相关函数可阻止修改对象的特性。

函数对象已设置为不可扩展的为每个属性将configurable设置为false为每个属性将writable设置为false
Object.preventExtensionsYesNoNo
Object.sealYesYesNo
Object.freezeYesYesYes

如果满足表中标记的所有条件,则以下函数返回true

函数函数对象是否可扩展为所有属性将configurable设置为false为所有数据属性将writable设置为false
Object.isExtensibleYesNoNo
Object.isSealedNoYesNo
Object.isFrozenNoYesYes

示例

下面的示例演示了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 标准模式。

如果你喜欢这篇文章,敬请给站长打赏↑

除特别注明外,本站所有文章均为本站站长原译,转载请注明出处。