类型错误:"x" 是只读的

当分配的全局变量或对象属性是只读属性时,会发生 JavaScript 严格模式-only 异常 "是只读的"。

¥The JavaScript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property.

信息

¥Message

TypeError: Cannot assign to read only property 'x' of #<Object> (V8-based)
TypeError: "x" is read-only (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)

错误类型

¥Error type

仅限 严格模式 中的 TypeError

¥TypeError in strict mode only.

什么地方出了错?

¥What went wrong?

分配给的全局变量或对象属性是只读属性。(从技术上讲,它是 不可写数据属性。)

¥The global variable or object property that was assigned to is a read-only property. (Technically, it is a non-writable data property.)

此错误仅发生在 严格模式代码 中。在非严格代码中,赋值会被默默地忽略。

¥This error happens only in strict mode code. In non-strict code, the assignment is silently ignored.

示例

¥Examples

无效案例

¥Invalid cases

只读属性并不常见,但可以使用 Object.defineProperty()Object.freeze() 创建它们。

¥Read-only properties are not super common, but they can be created using Object.defineProperty() or Object.freeze().

js
"use strict";
const obj = Object.freeze({ name: "Elsa", score: 157 });
obj.score = 0; // TypeError

("use strict");
Object.defineProperty(this, "LUNG_COUNT", { value: 2, writable: false });
LUNG_COUNT = 3; // TypeError

("use strict");
const frozenArray = Object.freeze([0, 1, 2]);
frozenArray[0]++; // TypeError

JavaScript 中还内置了一些只读属性。也许你尝试重新定义数学常数。

¥There are also a few read-only properties built into JavaScript. Maybe you tried to redefine a mathematical constant.

js
"use strict";
Math.PI = 4; // TypeError

抱歉,你不能这样做。

¥Sorry, you can't do that.

全局变量 undefined 也是只读的,因此你无法通过执行以下操作来消除臭名昭著的 "未定义不是一个函数" 错误:

¥The global variable undefined is also read-only, so you can't silence the infamous "undefined is not a function" error by doing this:

js
"use strict";
undefined = function () {}; // TypeError: "undefined" is read-only

有效案例

¥Valid cases

js
"use strict";
let obj = Object.freeze({ name: "Score", points: 157 });
obj = { name: obj.name, points: 0 }; // replacing it with a new object works

也可以看看