Object.seal
Object.seal()
方法可以让一个对象密封,并返回被密封后的对象。密封对象将会阻止向对象添加新的属性,并且会将所有已有属性的可配置性(configurable)置为不可配置(false),即不可修改属性的描述或删除属性。但是可写性描述(writable)为可写(true)的属性的值仍然可以被修改。
语法
Object.seal(obj)
参数
obj将要被密封的对象
返回值
被密封的物体。
描述
不会影响从原型链上继承的属性。但 __proto__
() 属性的值也会不能修改。
返回对传入的Object的引用。
例子
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)The definition of 'Object.seal' in that specification. | Standard | Initial definition. Implemented in JavaScript 1.8.5. |
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Object.seal' in that specification. | Standard | |
ECMAScript Latest Draft (ECMA-262)The definition of 'Object.seal' in that specification. | Living Standard | |
浏览器兼容性
Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic Support | 6 | (Yes) | 4 | 9 | 12 | 5.1 |
Feature | Android | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
---|---|---|---|---|---|---|---|
Basic Support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com