Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript class – can I make a "final" property?

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"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can make the property non-writable and non-configurable using Object.defineProperty:

class MyClass {
  someProperty = computeSomeValue();

  constructor() {
    Object.defineProperty(this, "someProperty", {
      writable: false,
      configurable: false,
    });
  }
}

or

class MyClass {
  constructor() {
    Object.defineProperty(this, "someProperty", {
      value: computeSomeValue(),
      writable: false,
      configurable: false,
    });
  }
}

That way, attempts to write to the property will cause an exception, just like with your setter-less getter property.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading