JavaScript / JavaScript Object-Oriented Programming (OOP)
Creating Classes and Objects
This tutorial focuses on creating classes and objects in JavaScript. It provides step-by-step instructions and practical examples.
Section overview
5 resourcesIntroduces OOP principles in JavaScript, including classes, objects, and inheritance.
1. Introduction
In this tutorial, we will delve into creating classes and objects in JavaScript. The primary goal is to equip you with the knowledge to define and create your own classes, and instantiate objects from them in a real-world context.
By the end of this tutorial, you will learn:
- What classes and objects are in JavaScript
- How to define classes and create objects
- How to apply methods and properties to a class
The prerequisites for this tutorial are a basic understanding of JavaScript syntax and knowledge of fundamental programming concepts such as variables, functions and control flow.
2. Step-by-Step Guide
Classes and Objects
In JavaScript, classes are a template for creating objects. They encapsulate data with code to manipulate that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics.
An object is an instance of a class. When a class is defined, no memory is allocated but when it is instantiated (i.e., an object is created) memory is allocated.
Defining a Class
To define a class in JavaScript, you use the class keyword, followed by the name of the class with a pair of curly braces {}.
class MyClass {
// class methods and properties go here
}
Creating an Object
After a class is defined, you can use the new keyword to create an object from the class.
let obj = new MyClass();
3. Code Examples
Example 1: Defining a Class and Creating an Object
class Car {
constructor(brand) { // Constructor method is a special method for creating and initializing an object
this.carBrand = brand; // this keyword refers to the object it belongs to
}
present() { // Class method
return `I have a ${this.carBrand}`;
}
}
let myCar = new Car("Toyota");
console.log(myCar.present()); // Logs: "I have a Toyota"
In this example, Car is a class and myCar is an object of the Car class. The Car class has a constructor which accepts a brand parameter and a method present to display the car's brand.
Example 2: Using Class Properties
class Car {
constructor(brand) {
this.carBrand = brand;
this.year = new Date().getFullYear(); // Current year
}
age() {
return `This ${this.carBrand} is ${new Date().getFullYear() - this.year} years old.`;
}
}
let myCar = new Car("Toyota");
console.log(myCar.age()); // Logs: "This Toyota is 0 years old."
In this example, we added another property year to the Car class and a method age to calculate the car's age.
4. Summary
In this tutorial, you have learned the basics of creating classes and objects in JavaScript. You have also learned how to define methods and properties for a class and how to instantiate an object from a class.
The next steps in your learning could be understanding inheritance in JavaScript, and how classes can be extended. You may also wish to learn more about other features of ES6, such as arrow functions and promises.
5. Practice Exercises
-
Define a class
Rectanglethat acceptswidthandheightas parameters. Add a methodareato calculate the area of the rectangle. -
Create an instance of
Rectangleand calculate the area.
Solution
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
let myRectangle = new Rectangle(5, 6);
console.log(myRectangle.area()); // Logs: 30
In this solution, we've created a Rectangle class with width and height properties. We've also added a method area that returns the product of width and height. When we create an instance of Rectangle and call the area method, it logs the area of the rectangle.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article