ArticleZip > Es6 Call Class Constructor Without New Keyword

Es6 Call Class Constructor Without New Keyword

When working with ES6 classes in JavaScript, understanding how to call a class constructor without using the 'new' keyword can be a handy trick to have up your sleeve. This can come in useful in certain scenarios where you want to manipulate the behavior of instances or work with existing objects that need to behave like instances of a class. Let’s dive into how you can achieve this in a few simple steps.

First off, before we get into the nitty-gritty of calling a class constructor without ‘new’, let’s quickly recap what a constructor is. In JavaScript, a constructor is a special method that gets called when you create a new instance of a class. It initializes the object's properties, sets default values, and performs any other setup needed for the instance.

To call a class constructor without using the ‘new’ keyword, you can take advantage of the ‘Object.create’ method provided by JavaScript. This method creates a new object with the specified prototype object and properties. Here’s how you can do it:

Javascript

class MyClass {
  constructor(param) {
    this.param = param;
  }

  myMethod() {
    return this.param;
  }
}

const myInstance = Object.create(MyClass.prototype);
MyClass.call(myInstance, 'Hello, world!');

console.log(myInstance.myMethod()); // Output: Hello, world!

In this example, we have a simple ES6 class ‘MyClass’ with a constructor that takes a parameter and a method ‘myMethod’ that returns the parameter value.

By using ‘Object.create’ to create a new object ‘myInstance’ with the prototype of ‘MyClass’, we can then call the constructor function of ‘MyClass’ with the specific argument we want. The ‘MyClass.call(myInstance, 'Hello, world!');’ line achieves just that.

Once you have called the constructor with the desired parameter value, you can then use the instance as you would with any regular instance of the class. In this case, we call the ‘myMethod’ function on ‘myInstance’ and get the expected output.

It’s important to note that while this method allows you to call a class constructor without using ‘new’, it might not always be the recommended approach in every situation. The ‘new’ keyword exists for a reason and provides a clear and widely understood way to create object instances from classes.

In conclusion, being able to call a class constructor without 'new' in ES6 classes can be a useful technique to have in your toolkit for specific scenarios where you need more control over object instantiation. By leveraging ‘Object.create’ and the ‘constructor.call’ method, you can achieve this without much hassle. As always, remember to consider the context and implications of your approach when working with JavaScript classes.