How to Create Classes and Objects

Learn the different ways to create classes and objects in JavaScript.

Introduction

Object-oriented programming allows us to easily develop very large projects, as well as expand them in the future. A class is a blueprint that helps to create different objects. An object is an instance of a class that denotes a real-world entity. For example, we can create a “Tree” class from which multiple objects can be created, such as “Maple” “Pine” and “Cherry.”

Everything in JavaScript is an object. Whether you create an array or even a function, all are treated as an object. There are multiple ways to create an object in JavaScript.

Option 1: Using JSON

The first and the most straightforward way to create an object is to create variables containing JSON data. JSON stands for JavaScript Object Notation, and is a standard for transferring data across servers.

Press + to interact
// Empty Object
const Car = {};
// Print the empty object
console.log(Car, typeof Car);
const Vehicle = {
speed: 80,
fuel: 60,
model: "ABD 123DS",
drive: function(){
console.log("Driving at ", this.speed, "km/hr");
}
}
// Print the properties of the Vehicle object
console.log("Vehicle Speed is: ", Vehicle.speed);
console.log("Vehicle Fuel is: ", Vehicle.fuel);
Vehicle.drive();
// Update the speed property of the Vehicle object
Vehicle.speed = 120;
console.log("Vehicle Speed is: ", Vehicle.speed);
Vehicle.drive();
// Add a new property to the Vehicle object
Vehicle.horse_power = 120;
console.log(Vehicle);

Explanation:

  • Line 2: We create an empty object using the curly brackets ({}).

  • Line 5: We print the value of the variable Car and the type of the variable Car ...