Skip to content

Instantly share code, notes, and snippets.

@e0ipso
Last active March 16, 2024 21:09
Show Gist options
  • Save e0ipso/8faddc9a362c31ddc9f9 to your computer and use it in GitHub Desktop.
Save e0ipso/8faddc9a362c31ddc9f9 to your computer and use it in GitHub Desktop.
Read only property ES6
/**
* Class that holds a read only property.
*/
class PropertyBag {
/**
* Accessor.
*
* @return {string}
* The value. This annotation can be used for type hinting purposes.
*/
static get readOnly() {
return 'This property can only be read.';
}
/**
* Mutator.
*
* @param {*} value
* The passed in value.
*
* @throws {Error}
* Inconditionally.
* @return {void}
*/
static set readOnly(value) {
throw new Error(`The readOnly property cannot be written. ${value} was passed.`);
}
}
console.log(PropertyBag.readOnly); // This property can only be read.
PropertyBag.readOnly = 'Ha!'; // Error: The readOnly property cannot be written. Ha! was passed.
@Davenchy
Copy link

Davenchy commented Aug 2, 2018

class Todo {
        constructor(data) {
                this.__getId__ = function () { return data.id };
        }

        get id() { return this.__getId__(); }
}

var todo = new Todo({id: 123456});

console.log(todo.id);        // return 123456

todo.id = 654321;

console.log(todo.id);        // return 123456

OR

class Todo {
        constructor(data) {
                this.__getId__ = function () { return data.id };
        }

        get id() { return this.__getId__(); }
        
        set id(v) { throw new Error('Todo id property is read only'); }

}

var todo = new Todo({id: 123456});

console.log(todo.id);        // return 123456

todo.id = 654321;        // throw error

console.log(todo.id);        // return 123456

@dipamsen
Copy link

The problem with this is that we cannot even change the value from within the class.

@Anvar571
Copy link

class Todo {
  #data
  constructor(data) {
    this.#data = data
  }

  get findData() {
    return this.#data;
  };

  set findData(value) {
    throw new Error("Todo findData property readonly")
  } 
}

const newTodo = new Todo({
  id: 1,
  name: "lorem",
  description: "lorem ipsum"
});

newTodo.findData = {
  id: 2,
  name: "lorem 2",
  description: "lorem ipsum 2"
}

console.log(newTodo.findData);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment