类型错误:无法定义属性 "x":"obj" 不可扩展

JavaScript 异常 "无法定义属性"x”:当 Object.preventExtensions() 将对象标记为不再可扩展时,会发生“"obj" 不可扩展”,因此该对象永远不会拥有超出其被标记为不可扩展时所具有的属性。

¥The JavaScript exception "can't define property "x": "obj" is not extensible" occurs when Object.preventExtensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible.

信息

¥Message

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)

错误类型

¥Error type

TypeError

什么地方出了错?

¥What went wrong?

通常,对象是可扩展的,并且可以向其添加新属性。然而,在这种情况下,Object.preventExtensions() 将一个对象标记为不再可扩展,因此它永远不会拥有超出其被标记为不可扩展时所具有的属性。

¥Usually, an object is extensible and new properties can be added to it. However, in this case Object.preventExtensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible.

示例

¥Examples

向不可扩展对象添加新属性

¥Adding new properties to a non-extensible objects

严格模式 中,尝试向不可扩展对象添加新属性会引发 TypeError。在草率模式下,添加的 "x" 属性会被默默忽略。

¥In strict mode, attempting to add new properties to a non-extensible object throws a TypeError. In sloppy mode, the addition of the "x" property is silently ignored.

js
"use strict";

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

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

严格模式 和草率模式下,向不可扩展对象添加新属性时,对 Object.defineProperty() 的调用都会抛出异常。

¥In both, strict mode and sloppy mode, a call to Object.defineProperty() throws when adding a new property to a non-extensible object.

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

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

要修复此错误,你需要完全删除对 Object.preventExtensions() 的调用,或者将其移动到某个位置,以便更早添加该属性,并且稍后将对象标记为不可扩展。当然,如果不需要,你也可以删除尝试添加的属性。

¥To fix this error, you will either need to remove the call to Object.preventExtensions() entirely, or move it to a position so that the property is added earlier and only later the object is marked as non-extensible. Of course you can also remove the property that was attempted to be added, if you don't need it.

js
"use strict";

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

Object.preventExtensions(obj);

也可以看看