I have a JavaScript class and I want to create a property that cannot be reassigned. In JavaScript, a const
would normally work, but I don’t know how to do this at the class level. In Java, I would use a "final" property.
Currently, I am using the following code:
class MyClass {
// I want this to never change after the first compute
"final" someProperty = computeSomeValue(); // computeSomeValue is imported
// one option is to use "get"
get someProperty() {
// issue is that the function is run each time this property is accessed and I'd need more logic to cache it.
return computeSomeValue();
}
}
Is there a better way to achieve this in JavaScript without using "get"?
3
Answers
You can make the property non-writable and non-configurable using
Object.defineProperty
:or
That way, attempts to write to the property will cause an exception, just like with your setter-less getter property.
You can use
Object.defineProperty
but it doesn’t throw an error when you try to modify the propertyEdit: it throws an error in strict mode
If you were using TypeScript (which you might like if you come from a Java background where things are more strongly typed), you could declare it to be
readonly
.However, when compiled to JavaScript this will still allow access since in the end it still outputs a JS class.
If your goal is only to let developers know this value shouldn’t be changed (just like
const
does), then this will work. If your goal is to prevent users from changing the code, there’s nothing you can do about that.