當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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






相關用法


注:本文由純淨天空篩選整理自 JavaScript Object.seal() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。