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

Advertisements

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

>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.

Leave a ReplyCancel reply