79230934

Date: 2024-11-27 15:45:40
Score: 0.5
Natty:
Report link

After you have received several good answers and accepted one of them, I would like an additional subtle point. Even if you perfectly apply Object.freeze, you can modify the class object itself. Note that a class object is nothing but a constructor function on steroids, essentially, it is a constructor that can be implemented as a strictly equivalent non-class constructor function.

The problem is that the class object or the constructor function object can be re-assigned:

// If you use
class A {/* ... */}
function MakeA() {/* ... */}

// you could accidentally reassign the object A and MakeA
A = function() {
    throw new Error("A is no longer functional");
};
// or
MakeA = function() {
    throw new Error("MakeA is no longer functional, too");
};

I did not invent this reassignment trick, I've found it in another question, and it looked scary to me. And this is what you don't want. If you are trying to protect some objects with Object.freeze, you certainly would like to protect the constructor objects from reassigning.

But why is it possible? Unfortunately, this is how the class and function definitions shown above work. They create variables, not constants. In other words, they are equivalent to

let A = class {/* ... */}
let MakeA = function () {/* ... */}

That is, A and MakeA are actually variable. And this is not what you want Now, it is obvious that you can do better:

const A = class {/* ... */}
const MakeA = function () {/* ... */}

These const forms of the definition of constructor objects can replace the forms class A {} or function B() {} everywhere, except in some rare and marginal cases. These const forms can make the code more stable.

Of course, on top of this, Object.freeze still should be used where it is required.

Reasons:
  • Blacklisted phrase (1): another question
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: Sergey A Kryukov