- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Destructuring
- Else
- Else if
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- Function
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Overriding methods
- Parameters
- Promises
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- Substring
- Template literals
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript Class: Creating Classes and Objects in JS
In JavaScript, a class is a blueprint for creating objects with predefined properties and methods. JavaScript classes provide a convenient way to create constructor functions and handle inheritance.
How to Use JavaScript Classes
Creating JavaScript Classes
A JavaScript class declaration syntax consists of the class
keyword followed by the class name. Within the curly braces of the class body, you can add class methods, including the class constructor
method.
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
class
: The keyword to create a class in JavaScript.constructor
: A special method for creating objects from the class. It allows you to initialize class properties when a JavaScript object is created.
The class syntax in JavaScript makes it easier to define reusable blueprints for objects.
Creating Instances of JavaScript Classes
To create a new object from a class, you need the new
keyword. Essentially, new
creates an object of the class by allocating memory for it and calling the constructor method:
let myCar = new Car("VW");
new
: The keyword to create an instance of a class, which triggers the class constructor.
JavaScript classes share some similarities with Java classes, but they follow a prototypal inheritance model.
// Java Example
class Car {
String model;
Car(String model) {
this.model = model;
}
}
When to Use JavaScript Classes
Classes in JavaScript are a fundamental component of object-oriented programming. A class is useful for creating multiple instances of a type of object with similar functionalities, encapsulation, and inheritance. JavaScript classes follow OOP principles, enabling encapsulation, inheritance, and polymorphism.
Creating Similar Objects
You can use a class to represent objects with similar functionalities or properties.
let square = new Rectangle(5, 5);
let poster = new Rectangle(2, 3);
Encapsulation
Also, classes help you encapsulate data. Encapsulation bundles data and methods that change or otherwise use data within a class. In doing so, it limits direct access to some of the object's components to prevent accidental changes.
Here's an example of encapsulation using a BankAccount
class:
class BankAccount {
#accountBalance; // Private field
constructor(initialBalance) {
this.#accountBalance = initialBalance;
}
deposit(amount) {
if (amount > 0) {
this.#accountBalance += amount;
console.log(`Deposit of $${amount} successful. Balance is now $${this.#accountBalance}.`);
} else {
console.log("Invalid deposit amount.");
}
}
withdraw(amount) {
if (amount > 0 && amount <= this.#accountBalance) {
this.#accountBalance -= amount;
console.log(`Withdrawal of $${amount} successful. Balance is now $${this.#accountBalance}.`);
} else {
console.log("Insufficient funds or invalid amount.");
}
}
get balance() {
return this.#accountBalance;
}
}
let myAccount = new BankAccount(1000);
myAccount.deposit(500); // Deposit $500
myAccount.withdraw(200); // Withdraw $200
console.log(`Current balance: $${myAccount.balance}`); // Access balance using getter
Encapsulation allows for conditional property access to maintain security.
class SafeBox {
#password = "secure123";
getPassword(userRole) {
return userRole === "admin" ? this.#password : "Access Denied";
}
}
Inheritance
Classes are beneficial for inheritance, where one class inherits the properties and methods of another.
class Square extends Rectangle {
constructor(side) {
super(side, side);
}
}
Examples of JavaScript Classes
JavaScript classes are ubiquitous in web and software development. Here are some simplified examples of classes:
User Accounts
Classes can manage user properties and methods, such as creating a new user account or updating user information.
class User {
constructor(username, email) {
this.username = username;
this.email = email;
}
updateEmail(newEmail) {
this.email = newEmail;
}
}
let user1 = new User("johnDoe", "john@example.com");
HTML forms and JavaScript classes work together to manage user interactions.
class FormHandler {
constructor(formId) {
this.form = document.getElementById(formId);
}
}
Use with APIs
Classes often work with APIs to structure and manipulate data retrieved from a server.
class APIService {
static fetchData(url) {
return fetch(url).then(response => response.json());
}
}
Game Characters
In game development, classes can define properties and actions of characters, enhancing reusability and scalability.
class Character {
constructor(name, strength) {
this.name = name;
this.strength = strength;
}
attack() {
console.log(`${this.name} attacks with strength ${this.strength}`);
}
}
let hero = new Character("Warrior", 75);
Storing multiple values
Classes can also contain arrays to store multiple values inside an object.
class Library {
constructor() {
this.books = [];
}
addBook(book) {
this.books.push(book);
}
}
Improving UI compontents
JavaScript classes can be used to dynamically modify CSS styles for UI components.
class Theme {
constructor(theme) {
this.theme = theme;
}
applyTheme() {
document.body.classList.add(this.theme);
}
}
Animations
Classes can also manage animations in JavaScript for smoother UI transitions.
class Animator {
static fadeOut(element) {
element.style.transition = "opacity 1s";
element.style.opacity = "0";
}
}
Simplifying Iteration
Classes can help simplify iteration through lists of objects.
class BookCollection {
constructor() {
this.books = [];
}
addBook(book) {
this.books.push(book);
}
listBooks() {
this.books.forEach(book => console.log(book));
}
}
Learn More About JavaScript Classes
Static Methods
Static methods are methods that belong to a class itself, not to the instances of the class. Classes often use static methods to create utility functions for an application. To create static method, use the static
keyword at the beginning of the function's declaration.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
Static methods can also be async, allowing the use of await
inside the function.
class DataFetcher {
static async getData(url) {
let response = await fetch(url);
return response.json();
}
}
Static Properties
Static properties store class-level data, as opposed to the instance-level data of object properties. A static property can be useful for caches and configurations. To create a static property, add static
in front of a property’s declaration.
class Battery {
static voltage = 12; // Static property
constructor(capacity) {
this.capacity = capacity;
}
}
console.log(Battery.voltage); // Accessing the static property
Getter and Setter Methods
Getter and setter methods allow you to define methods in a class that look and behave like properties. Getters and setters allow you to get and set the values of properties with additional checks or control mechanisms. To create a getter or setter method, use the get
or set
keyword with the property name like in a function declaration.
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
// Getter to convert celsius to fahrenheit
get fahrenheit() {
return this.celsius * 1.8 + 32;
}
// Setter to set the temperature in celsius based on fahrenheit input
set fahrenheit(value) {
this.celsius = (value - 32) / 1.8;
}
}
let temp = new Temperature(25); // Setting temperature in Celsius
console.log(`${temp.celsius}°C is equivalent to ${temp.fahrenheit}°F.`); // Using getter to show Fahrenheit
temp.fahrenheit = 86; // Setting temperature using Fahrenheit
console.log(`86°F is equivalent to ${temp.celsius.toFixed(2)}°C.`); // Showing updated Celsius using the setter
Private Fields
Private fields (or private properties) are properties that are only accessible from within a class. To create a private field, use a hash (#
) in front of the variable declaration.
class Counter {
#count = 0;
increment() {
this.#count++;
}
get value() {
return this.#count;
}
}
Reusability
JavaScript classes can be structured using modules, allowing better code organization and reusability.
// File: Car.js
export class Car {
constructor(model) {
this.model = model;
}
}
// File: main.js
import { Car } from "./Car.js";
let myCar = new Car("Tesla");
Manipulating DOM
JavaScript classes are often used to manipulate the DOM, making elements dynamic.
class ElementHandler {
constructor(id) {
this.element = document.getElementById(id);
}
}
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.