类型错误:设置仅 getter 属性 "x"
当尝试为仅指定了 getter 的属性设置新值时,会发生 JavaScript 严格模式-only 异常 "设置仅 getter 属性"。
¥The JavaScript strict mode-only exception "setting getter-only property" occurs when there is an attempt to set a new value to a property for which only a getter is specified.
信息
错误类型
什么地方出了错?
示例
没有 setter 的属性
¥Property with no setter
下面的示例展示了如何为属性设置 getter。它没有指定 setter,因此在尝试将 temperature
属性设置为 30
时将抛出 TypeError
。有关更多详细信息,另请参阅 Object.defineProperty()
页面。
¥The example below shows how to set a getter for a property.
It doesn't specify a setter, so a
TypeError
will be thrown upon trying to set the temperature
property to 30
. For more details see also the
Object.defineProperty()
page.
"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"
要修复此错误,你需要删除尝试设置温度属性的 arc.temperature = 30
行,或者你需要为其实现 setter,例如:
¥To fix this error, you will either need to remove the arc.temperature = 30
line, which attempts to
set the temperature property, or you will need to implement a setter for it, for
example like this:
"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 }]