Skip to content

JavaScript class without constructor | Code

  • by

You can define a class without a constructor in JavaScript. If you do not specify a constructor method a default constructor is used.

By default, the constructor is defined as The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructors.

constructor() {}

For inheritance, we use this constructor to call superclass as :

constructor() {
    super.call()
}

JavaScript class without constructor

Simple example no error if you don’t use a constructor in the class.

<!DOCTYPE html>
<html>
<body>
  <script>
    class myClass {
      
    }

    var v = new myClass();
    console.log(v);
  </script>
</body>
</html> 

Output:

JavaScript class without constructor

ES6: call the class constructor without a new keyword

Constructors require the use of the new operator to create a new instance, as such invoking a class without the new operator results in an error, as it’s required for the class constructor to create a new instance.

The error message is also quite specific, and correct

TypeError: Class constructors cannot be invoked without ‘new’

You could;

  • either uses a regular function instead of a class1.
  • Always call the class with new.
  • Call the class inside a wrapping regular function, always using new, that way you get the benefits of classes, but the wrapping function can still be called with and without the new operator

Source: stackoverflow.com

Here’s an example of a JavaScript class without a constructor:

class Person {
  // No constructor defined
  // Other class methods and properties can be defined here
  // ...
  
  // Example method
  sayHello() {
    console.log("Hello, I'm a person.");
  }
}

// Create an instance of the Person class
const person = new Person();

// Call a method on the instance
person.sayHello(); // Output: Hello, I'm a person.

In this example, the Person class does not have an explicit constructor, but you can still create instances of the class and call its methods. If you don’t need to perform any setup or initialization when creating instances, this default behavior is perfectly fine. However, if you need to perform some setup during object creation, you can define a constructor method within the class.

Do comment if you have any 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 *