JavaScript Object.seal() 方法
JavaScript的 Object.seal() 方法可以将一个对象封闭起来,防止添加新属性,并将所有现有属性标记为不可配置。需要封闭的对象作为参数传递给该方法,并且该方法返回被封闭的对象。
语法:
Object.seal(obj)
参数:
obj :应该被封闭的对象。
返回值:
Object.sealed() 方法返回已被封闭的对象。
浏览器支持:
Chrome | 6 |
---|---|
Edge | Yes |
Firefox | 4 |
Opera | 12 |
示例1
const obj1 = { property1: 'Marry'};
const obj2 = Object.seal(obj1);
// prevents other code from deleting properties of an object.
obj2.property1 = 'carry';
console.log(obj2.property1);
输出:
"carry"
示例2
const object1 = {
property1: 29
};
Object.seal(object1);
// Prevents other code from deleting properties of an object.
object1.property1 =45;
console.log(object1.property1);
delete object1.property1;
// cannot delete when sealed
输出:
45
示例3
const object1 = {
property1: 42
};
Object.seal(object1);
object1.property1 = 45;
console.log(object1.property1);
delete object1.property1; // cannot delete when sealed
console.log(object1.property1);
const object2 = {
property2: 45};
object2.property2 =67;
console.log(object2.property2);
输出:
45
45
67