// Private constructor to prevent instantiation function UtilityClass() { throw new Error("This class cannot be instantiated."); }
// Static utility method UtilityClass.utilityMethod = function () { console.log("This is a utility method."); };
return UtilityClass;})(); // Usage UtilityClass.utilityMethod(); // Works fine try {
const obj = new UtilityClass(); // Throws an error} catch (e) {
console.error(e.message); // Outputs: "This class cannot be instantiated."} ``` In this example, the `UtilityClass` function is encapsulated within an immediately invoked function expression (IIFE), which effectively hides the constructor and enforces noninstantiability by throwing an error if instantiation is attempted. ==Example 2: Enforcing Noninstantiability with a Static Class in JavaScript== You can also enforce noninstantiability by using static methods and a private constructor: ```javascript class MathUtils {
// Private constructor to prevent instantiation constructor() { throw new Error("This class cannot be instantiated."); }
// Static utility methods static add(a, b) { return a + b; }
static subtract(a, b) { return a - b; }} // Usage console.log(MathUtils.add(10, 5