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

A simple example code uses 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);

Another example:

var MyClass = (function() {
  // Private variable
  var privateVariable = "I am private";

  // Private constructor
  function MyClassConstructor() {
    // Public method
    this.publicMethod = function() {
      console.log("I am a public method");
    };

    // Private method
    var privateMethod = function() {
      console.log("I am a private method");
    };

    // Public method that can access private members
    this.accessPrivateMethod = function() {
      privateMethod();
    };
  }

  // Return the constructor function
  return MyClassConstructor;
})();

// Usage
var myObject = new MyClass();
myObject.publicMethod(); // Output: I am a public method
myObject.accessPrivateMethod(); // Output: I am a private method
// myObject.privateMethod(); // Error: privateMethod is not a function
// console.log(myObject.privateVariable); // undefined

In this example, the MyClass constructor is encapsulated within an immediately invoked function expression (IIFE). The privateVariable and privateMethod are private to the constructor and cannot be accessed directly from outside. Public methods like publicMethod and accessPrivateMethod are accessible from the instances of MyClass.

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. Required fields are marked *