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);

另见