Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot assign to read only property

Tags:

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.

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

like image 935
larrydalmeida Avatar asked Dec 17 '14 06:12

larrydalmeida


People also ask

What is read only property in JavaScript?

The readOnly property sets or returns whether a text field is read-only, or not. A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it. Tip: To prevent the user from interacting with the field, use the disabled property instead.

Why is object read only JavaScript?

The JavaScript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property.

How do you assign values to readonly property in typescript?

Sample Code: class C { readonly readOnlyProperty: string; constructor(raw: string) { this. process(raw); } process(raw: string) { this. readOnlyProperty = raw; // [ts] Cannot assign to 'readOnlyProperty' because it is a constant or a read-only property. } }

Is read only error in JavaScript?

This JavaScript exception is read-only works in strict mode-only and It occurs if a global variable or object property which has assigned to a value, is a read-only property. Cause of Error: The global variable or object property that has assigned value is a read-only property.


1 Answers

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.

like image 93
Leo Avatar answered Sep 21 '22 08:09

Leo