...
/How to Create Classes and Objects
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.
// Empty Objectconst Car = {};// Print the empty objectconsole.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 objectconsole.log("Vehicle Speed is: ", Vehicle.speed);console.log("Vehicle Fuel is: ", Vehicle.fuel);Vehicle.drive();// Update the speed property of the Vehicle objectVehicle.speed = 120;console.log("Vehicle Speed is: ", Vehicle.speed);Vehicle.drive();// Add a new property to the Vehicle objectVehicle.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 variableCar
...