skip to Main Content

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


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

    Login or Signup to reply.
  2. You can use Object.defineProperty but it doesn’t throw an error when you try to modify the property

    Edit: it throws an error in strict mode

    'use strict'
    class MyClass {
      constructor() {
        Object.defineProperty(this, 'final', {
          configurable: false,
          writable: false,
          value: 123
        })
      }
    }
    
    const x = new MyClass()
    
    console.log(x.final)
    
    x.final = 4
    
    console.log(x.final)
    Login or Signup to reply.
  3. 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.

    class MyClass {
      readonly someProperty = computeSomeValue();
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search