Uncaught TypeError: Cannot assign to read only property

后端 未结 3 2145
执念已碎
执念已碎 2020-12-15 14:42

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

相关标签:
3条回答
  • 2020-12-15 15:32

    I tried changing year to a different term, and it worked.

    public_methods : {
        get: function() {
            return this._year;
        },
    
        set: function(newValue) {
            if(newValue > this.originYear) {
                this._year = newValue;
                this.edition += newValue - this.originYear;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-15 15:33

    If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.

    var globalObject = {
        name:"a",
        age:20
    }
    function() {
        let localObject = {
        name:'a',
        age:21
        }
        this.globalObject = localObject;
    }
    
    0 讨论(0)
  • 2020-12-15 15:42

    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.

    0 讨论(0)
提交回复
热议问题