Skip to content

JavaScript static class | Code

  • by

The static class cannot be instantiated, you can’t use the new keyword to create an object of the class type. There is no static class concept in JavaScript.

But you can prevent a class from being instantiated by using a constructor function throwing an error.

JavaScript static class

Simple example code uses an if statement and instanceof method to find the object type.

<!DOCTYPE html>
<html>
<body>
  <script>
    class StaticClass {  constructor() {
      if (this instanceof StaticClass) {
        throw Error('A static class cannot be instantiated.');
      }
    }  static method() {}}

    let test = new StaticClass();
  </script>
</body>
</html> 

Output:

JavaScript static class

Here’s how you can create something that resembles a static class in JavaScript:

// Define a JavaScript "static class" using an object and functions.

const MyStaticClass = {
  // Static properties
  staticProperty: "I am a static property",

  // Static methods
  staticMethod: function() {
    return "I am a static method";
  }
};

// You can access the static property and method as follows:
console.log(MyStaticClass.staticProperty); // "I am a static property"
console.log(MyStaticClass.staticMethod());   // "I am a static method"

In the example above, MyStaticClass is an object that encapsulates both static properties and static methods. You can access these properties and methods directly through the object, as you would with a traditional static class.

Keep in mind that in JavaScript, there is no strict enforcement of access control like in some other languages, so properties and methods of an object can still be modified or extended. However, it’s a common convention to use uppercase letters for the names of objects that are intended to be used as static classes to indicate their special purpose.

If you’re working with ES6 (ECMAScript 2015) or later, you can also use the class syntax and static methods to create a more class-like structure:

class MyStaticClass {
  static staticProperty = "I am a static property";

  static staticMethod() {
    return "I am a static method";
  }
}

console.log(MyStaticClass.staticProperty); // "I am a static property"
console.log(MyStaticClass.staticMethod());   // "I am a static method"

This approach provides more structure and is similar to how static classes work in some other programming languages.

Do comment if you have any doubts or suggestions on this JS class topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

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

Continue reading