Object.isExtensible()
Object.isExtensible() 靜態方法用於判斷一個物件是否是可擴充套件的(即是否可以向其中新增新屬性)。
試一試
const object = {};
console.log(Object.isExtensible(object));
// Expected output: true
Object.preventExtensions(object);
console.log(Object.isExtensible(object));
// Expected output: false
語法
js
Object.isExtensible(obj)
引數
obj-
需要檢查的物件。
返回值
一個 Boolean 值,指示給定的物件是否可擴充套件。
描述
預設情況下,物件是可擴充套件的:可以向它們新增新屬性,並且它們的 [[Prototype]] 可以被重新分配。可以使用 Object.preventExtensions()、Object.seal()、Object.freeze() 或 Reflect.preventExtensions() 中的任何一個來將物件標記為不可擴充套件。
示例
使用 Object.isExtensible
js
// New objects are extensible.
const empty = {};
Object.isExtensible(empty); // true
// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false
// Sealed objects are by definition non-extensible.
const sealed = Object.seal({});
Object.isExtensible(sealed); // false
// Frozen objects are also by definition non-extensible.
const frozen = Object.freeze({});
Object.isExtensible(frozen); // false
非物件引數
在 ES5 中,如果此方法的引數不是物件(即原始型別),則會引發 TypeError。在 ES2015 中,如果傳遞了非物件引數,它將返回 false 而不會引發任何錯誤,因為原始型別根據定義是不可變的。
js
Object.isExtensible(1);
// TypeError: 1 is not an object (ES5 code)
Object.isExtensible(1);
// false (ES2015 code)
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-object.isextensible |
瀏覽器相容性
載入中…