未捕获的TypeError:无法分配为只读属性 [英] Uncaught TypeError: Cannot assign to read only property
问题描述
我正在尝试Nicholas Zakas撰写的《 Web开发人员的专业JavaScript》一书中的一个非常简单的示例,但是我不知道我在这里做错了什么.一定是我错过的非常简单的事情,但是我被卡住了.
I was trying out this really simple example from the awesome "Professional JavaScript for Web Developers" book by Nicholas Zakas but I can't figure what I am doing wrong here. Must be something really simple that I missed but I'm stuck.
这是代码:
'use strict';
var book = {};
Object.defineProperties(book, {
originYear: {
value: 2004,
writable: false
},
_year: {
value: 2004
},
edition: {
value: 1
},
year : {
get: function() {
return this._year;
},
set: function(newValue) {
if(newValue > this.originYear) {
this._year = newValue;
this.edition += newValue - this.originYear;
}
}
}
});
console.log(book.edition);
book.year = 2006;
console.log(book.edition);
我在Chrome控制台上遇到的错误是:
The error I am getting on the Chrome console is:
未捕获的TypeError:无法分配为只读#main.js:31 Object.defineProperties.year.setmain.js:39的属性"_year"(匿名函数)
有人可以解释我哪里出了问题吗?
Can someone please explain where I have gone wrong?
这是小提琴
推荐答案
使用 Object.defineProperties
时,默认情况下 writable
设置为 false 代码>,因此
_year
和版本
实际上是只读属性.
When you use Object.defineProperties
, by default writable
is set to false
, so _year
and edition
are actually read only properties.
将它们明确设置为可写:true
:
_year: {
value: 2004,
writable: true
},
edition: {
value: 1,
writable: true
},
签出 此方法的MDN .
可写
true
,并且仅当与该属性关联的值可以使用赋值运算符进行更改时.
默认为false
.
writable
true
if and only if the value associated with the property may be changed with an assignment operator.
Defaults tofalse
.
这篇关于未捕获的TypeError:无法分配为只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!