Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - Uncaught TypeError: Cannot assign to read only property

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.

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:

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

Can someone please explain where I have gone wrong?

Here is the fiddle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you use Object.defineProperties, by default writable is set to false, so _year and edition are actually read only properties.

Explicitly set them to writable: true:

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

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

Check out MDN for this method.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...