Object.seal()

Object.seal()方法封闭一个对象,阻止添加新属性并将所有现有属性标记为不可配置。当前属性的值只要可写就可以改变。
 

语法

Object.seal(obj)

参数

obj
将要被密封的对象。

返回值

被密封的对象。

描述

通常,一个对象是严格模式 中最常见的,但不唯一)。

不会影响从原型链上继承的属性。但  ) 属性的值也会不能修改。

返回被密封对象的引用。

例子

var obj = {
  prop: function() {},
  foo: 'bar'
};

// New properties may be added, existing properties
// may be changed or removed.
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;

var o = Object.seal(obj);

o === obj; // true
Object.isSealed(obj); // === true

// Changing property values on a sealed object
// still works.
obj.foo = 'quux';

// But you can't convert data properties to accessors,
// or vice versa.
Object.defineProperty(obj, 'foo', {
  get: function() { return 'g'; }
}); // throws a TypeError

// Now any changes, other than to property values,
// will fail.
obj.quaxxor = 'the friendly duck';
// silently doesn't add the property
delete obj.foo;
// silently doesn't delete the property

// ...and in strict mode such attempts
// will throw TypeErrors.
function fail() {
  'use strict';
  delete obj.foo; // throws a TypeError
  obj.sparky = 'arf'; // throws a TypeError
}
fail();

// Attempted additions through
// Object.defineProperty will also throw.
Object.defineProperty(obj, 'ohai', {
  value: 17
}); // throws a TypeError
Object.defineProperty(obj, 'foo', {
  value: 'eit'
}); // changes existing property value

注意

在ES5中,如果这个方法的参数不是一个(原始)对象,那么它将导致TypeError。在ES2015中,非对象参数将被视为已被密封的普通对象,会直接返回它。

Object.seal(1);
// TypeError: 1 is not an object (ES5 code)

Object.seal(1);
// 1                             (ES2015 code)

对比 Object.freeze()

使用Object.freeze()冻结的对象中的现有属性是不可变的。用Object.seal()密封的对象可以改变其现有属性。

规范

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
Object.seal
Standard Initial definition. Implemented in JavaScript 1.8.5.
ECMAScript 2015 (6th Edition, ECMA-262)
Object.seal
Standard  
ECMAScript Latest Draft (ECMA-262)
Object.seal
Draft  

浏览器兼容

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
seal Chrome Full support 6 Edge Full support 12 Firefox Full support 4 IE Full support 9 Opera Full support 12 Safari Full support 5.1 WebView Android Full support Yes Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes nodejs Full support Yes

Legend

Full support  
Full support

相关链接