Javascript 未捕获的类型错误:无法分配给只读属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27519836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:15:28  来源:igfitidea点击:

Uncaught TypeError: Cannot assign to read only property

javascript

提问by Larrydx

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.

我正在尝试 Nicholas Zakas 所著的很棒的“Web 开发人员专业 JavaScript”一书中的这个非常简单的示例,但我无法弄清楚我在这里做错了什么。一定是我错过的一些非常简单的事情,但我被卡住了。

Here is the code:

这是代码:

'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);

The error I am getting on the Chrome console is:

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

Uncaught TypeError: Cannot assign to read only property '_year' of #main.js:31 Object.defineProperties.year.setmain.js:39 (anonymous function)

未捕获的类型错误:无法分配给 #main.js:31 Object.defineProperties.year.setmain.js:39(匿名函数)的只读属性“_year”

Can someone please explain where I have gone wrong?

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

Here is the fiddle

这是小提琴

采纳答案by Leo

When you use Object.defineProperties, by default writableis set to false, so _yearand editionare actually read onlyproperties.

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

Explicitly set them to writable: true:

将它们显式设置为writable: true

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

edition: {
    value: 1,
    writable: true
},

Check out MDN for this method.

请查看MDN 了解此方法

writable
trueif and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.

writable
true当且仅当与属性关联的值可以通过赋值运算符进行更改时。
默认为false.

回答by Rutwick Gangurde

I tried changing yearto a different term, and it worked.

我尝试改用year不同的术语,它奏效了。

public_methods : {
    get: function() {
        return this._year;
    },

    set: function(newValue) {
        if(newValue > this.originYear) {
            this._year = newValue;
            this.edition += newValue - this.originYear;
        }
    }
}