未捕获的TypeError:无法分配给只读属性

Lar*_*ydx 49 javascript

我正在尝试这个非常简单的例子来自Nicholas Zakas的"专业JavaScript for Web Developers"一书,但是我无法想象我在这里做错了什么.一定是我错过的非常简单的东西,但我被困住了.

这是代码:

'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);
Run Code Online (Sandbox Code Playgroud)

我在Chrome控制台上遇到的错误是:

未捕获的TypeError:无法分配给#main.js的只读属性'_year':31 Object.defineProperties.year.setmain.js:39(匿名函数)

有人可以解释我哪里出错了吗?

这是小提琴

Leo*_*Leo 37

当您使用Object.defineProperties,默认writable设置为false,因此_yearedition实际只读属性.

明确地将它们设置为writable: true:

_year: {
    value: 2004,
    writable: true
},

edition: {
    value: 1,
    writable: true
},
Run Code Online (Sandbox Code Playgroud)

查看MDN以了解此方法.

writable
true当且仅当与属性关联的值可以使用赋值运算符更改时.
默认为false.

  • 感谢您的回答,因为它引导我找到我的解决方案.我有一个变量:`var thisObject = {name:'a name',id:1};`并且在代码中的某个时刻我设置了`thisObject = 1;`(我认为它是旧代码或者只是没有'写得正确...当我尝试使用或设置`thisObject.name`之后我收到此错误消息.删除我将`thisObject`设置为整数的行修复了我的问题.希望这有助于某人. (3认同)