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.setPrototypeOf()用法及代碼示例
- JavaScript Object.assign()用法及代碼示例
- JavaScript Object.getOwnPropertyDescriptors()用法及代碼示例
- JavaScript Object.getOwnPropertySymbols()用法及代碼示例
- JavaScript Object.defineProperties()用法及代碼示例
- JavaScript Object.freeze()用法及代碼示例
- JavaScript Object.preventExtensions()用法及代碼示例
- JavaScript Object.getOwnPropertyDescriptor()用法及代碼示例
- JavaScript Object.getOwnPropertyNames()用法及代碼示例
- JavaScript Object.getPrototypeOf()用法及代碼示例
- JavaScript Object.defineProperty()用法及代碼示例
- JavaScript Object.is()用法及代碼示例
- JavaScript Object.values()用法及代碼示例
- JavaScript Object.create()用法及代碼示例
- JavaScript Object.entries()用法及代碼示例
- JavaScript Uint8Array.of()用法及代碼示例
- JavaScript BigInt.prototype.toString()用法及代碼示例
- JavaScript DataView.getInt16()用法及代碼示例
- JavaScript Symbol.keyFor()用法及代碼示例
- JavaScript handler.has()用法及代碼示例
注:本文由純淨天空篩選整理自 JavaScript Object.seal() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。