📜  Javascript Object seal()方法

📅  最后修改于: 2020-10-25 11:46:19             🧑  作者: Mango

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