create an instance of a class in javascript

To create an instance of a class in JavaScript, you can use the new keyword followed by the name of the class and any arguments that the constructor function expects. Here's an example:

index.tsx
class Car {
  constructor(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
  }
  
  honk() {
    console.log("Beep beep!");
  }
}

const myCar = new Car("Honda", "Civic", 2020);
console.log(myCar); // output: Car { make: "Honda", model: "Civic", year: 2020 }
299 chars
15 lines

In the above code, we define a Car class with a constructor function that takes three arguments (make, model, and year). We also define a honk method on the prototype of the class.

To create an instance of the Car class, we use the new keyword followed by the name of the class and the arguments that the constructor function expects. We store a reference to the instance in a variable named myCar. Finally, we log the contents of myCar, which shows us that it is an instance of the Car class with the properties we passed to its constructor function.

gistlibby LogSnag