訊息
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