Last active
March 16, 2024 21:09
-
-
Save e0ipso/8faddc9a362c31ddc9f9 to your computer and use it in GitHub Desktop.
Read only property ES6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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. |
The problem with this is that we cannot even change the value from within the class.
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
OR