How to Create a New Object from a Class in JavaScript?

Estimated read time 1 min read

In JavaScript, you can create a new object from a class using the new keyword, followed by the constructor function of the class. Here’s an example of how to do this:

class Car {
  constructor(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
  }
}

const myCar = new Car('Toyota', 'Camry', 2020);
console.log(myCar); // outputs: Car { make: 'Toyota', model: 'Camry', year: 2020 }

In this example, the Car class has a constructor function that takes three parameters: make, model, and year. The new keyword creates a new instance of the Car class, and the constructor function is called with the specified values for each of the parameters. The resulting myCar object is an instance of the Car class, with the properties make, model, and year set to the values that were passed in.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply