TypeError: 设置只读属性 "x"
消息
TypeError: Cannot set property x of #<Object> which has only a getter (V8-based) TypeError: '#x' was defined without a setter (V8-based) TypeError: setting getter-only property "x" (Firefox) TypeError: Attempted to assign to readonly property. (Safari) TypeError: Trying to access an undefined private setter (Safari)
错误类型
哪里出错了?
示例
没有 setter 的属性
下面的示例演示如何为属性设置 getter。它没有指定 setter,因此在尝试将 temperature
属性设置为 30
时将抛出 TypeError
。有关更多详细信息,还可以参阅 Object.defineProperty()
页面。
js
"use strict";
function Archiver() {
const temperature = null;
Object.defineProperty(this, "temperature", {
get() {
console.log("get!");
return temperature;
},
});
}
const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 30;
// TypeError: setting getter-only property "temperature"
要修复此错误,您需要删除尝试设置 temperature 属性的 arc.temperature = 30
行,或者需要为此实现 setter,例如这样
js
"use strict";
function Archiver() {
let temperature = null;
const archive = [];
Object.defineProperty(this, "temperature", {
get() {
console.log("get!");
return temperature;
},
set(value) {
temperature = value;
archive.push({ val: temperature });
},
});
this.getArchive = function () {
return archive;
};
}
const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]