Skip to content

JavaScript private constructor | Example code

  • by

JavaScript private constructor means Changing the scope of a constructor to private removes our ability to use the new keyword.

class User {
      public name: string;

      private constructor (name: string) {
        this.name = name;
      }

      const user: User = new User('ABC'); // error

JavaScript private constructor

Simple example code use a variable (initializing) inside a closure which can throw an error if the constructor was called directly instead of via a class method:

In this example where MyClass would be a singleton that has a factory method create that allows creating MyClass instances.

<!DOCTYPE html>
<html>
<body>
  <script>
    var MyClass = (function() {
      function MyClass() {
        this.initialized = false;
        
      }

      MyClass.prototype = {
        init: function () {
          this.initialized = true;
          return this;
        }
      };

      return {
        create: function () {
          return new MyClass().init();   
        }
      };

    })();


    var m = MyClass.create();
    console.log(m);
    console.log(m.constructor); //Will be Object because we replaced the whole prototype

    new MyClass();
  </script>

</body>
</html> 

Output:

JavaScript private constructor

Source: stackoverflow.com/

Accessing a private constructor

Create a static method that constructs an instance.

class Foo {
    private constructor(private x: number) {}

    /** @internal */
    static createForTesting(x: number) {
        return new Foo(x);
    }
}

const instance = Foo.createForTesting(5);

Do comment if you have doubts or suggestions on this Js constructor 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.