消息
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)
错误类型
哪里出错了?
被赋值的全局变量或对象属性是只读属性。(严格来说,它是一个不可写的自有属性。)
这个错误只发生在严格模式代码中。在非严格模式代码中,赋值会被静默忽略。
示例
无效案例
只读属性并不常见,但它们可以使用 Object.defineProperty() 或 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 中也有一些内置的只读属性。也许你尝试重新定义一个数学常量。
js
"use strict";
Math.PI = 4; // TypeError
抱歉,你不能那样做。
全局变量 undefined 也是只读的,所以你无法通过这样做来消除臭名昭著的“undefined is not a function”错误
js
"use strict";
undefined = function () {}; // TypeError: "undefined" is read-only
有效情况
js
"use strict";
let obj = Object.freeze({ name: "Score", points: 157 });
obj = { name: obj.name, points: 0 }; // replacing it with a new object works