TypeError: can't define property "x": "obj" is not extensible

Object.preventExtensions() 將一個物件標記為不再可擴充套件時,就會發生 JavaScript 異常 "無法定義屬性 "x":"obj" 不可擴充套件",因此該物件將永遠不會擁有超出其被標記為不可擴充套件時所擁有的屬性。

訊息

TypeError: Cannot add property x, object is not extensible (V8-based)
TypeError: Cannot define property x, object is not extensible (V8-based)
TypeError: can't define property "x": Object is not extensible (Firefox)
TypeError: Attempting to define property on object that is not extensible. (Safari)

錯誤型別

TypeError

哪裡出錯了?

通常,物件是可擴充套件的,可以向其新增新屬性。但是,在這種情況下,Object.preventExtensions() 將一個物件標記為不再可擴充套件,因此它將永遠不會擁有超出其被標記為不可擴充套件時所擁有的屬性。

示例

向不可擴充套件物件新增新屬性

嚴格模式下,嘗試向不可擴充套件物件新增新屬性會丟擲 TypeError。在鬆散模式下,新增“x”屬性會被靜默忽略。

js
"use strict";

const obj = {};
Object.preventExtensions(obj);

obj.x = "foo";
// TypeError: can't define property "x": Object is not extensible

嚴格模式和鬆散模式下,當向不可擴充套件物件新增新屬性時,呼叫 Object.defineProperty() 都會丟擲錯誤。

js
const obj = {};
Object.preventExtensions(obj);

Object.defineProperty(obj, "x", { value: "foo" });
// TypeError: can't define property "x": Object is not extensible

要解決此錯誤,您需要完全刪除對 Object.preventExtensions() 的呼叫,或者將其移動到屬性在物件被標記為不可擴充套件之前新增的位置。當然,如果不需要,您也可以刪除嘗試新增的屬性。

js
"use strict";

const obj = {};
obj.x = "foo"; // add property first and only then prevent extensions

Object.preventExtensions(obj);

另見