简体   繁体   中英

What is the definition of a read-only property in JavaScript? What does it mean?

I am a little confused on what a read-only property means? I know that classList is a read only property by MDN's definition but what does that exactly mean?

A read-only property means it cannot be overwritten or assigned to. Any such assignment will silently do nothing in non-strict mode. Eg:

 var obj = {}; Object.defineProperty(obj, 'property', {value: 123, writeable: false}) // Assign 456 to obj.property using the. syntax, but it's still 123 obj.property = 456; console.log(obj.property); // Assign 789 to obj.property using the [] syntax, but it's still 123 obj['property'] = 789; console.log(obj['property']);

Or just error out with a TypeError in strict mide:

 'use strict'; var obj = {}; Object.defineProperty(obj, 'property', {value: 123, writeable: false}) // Assign 456 to obj.property in strict mode will result in a TypeError obj.property = 456; console.log(obj.property);

Beside what @Mureinik said there is another way to make an object in read-only mode it called freeze you could use it like this example

 let myObj = {id: 45, title: 'title here'} Object.freeze(myObj); myObj.title = 'update title' // this wouldn't updates console.log(myObj) // incase if you want to rewrite this object after freezing it // you need to re-assign all of its values like this myObj = {id: myObj.id, title: 'Another title here'} console.log(myObj)

you could read about Object.freeze() and the right way to update it in mdn docs

When a property is read-only, the property is said to be “non-writable”. It cannot be reassigned.

for example you can not update or assign a value to the classList property of an element but you can read it.

For reference:

  1. Objects — Writable, Configurable & Enumerable
  2. JavaScript Object Accessors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM