start learning
Image 1
444758697080747

JavaScript Object-Oriented Programming (OOP)
CLASSES


Simple Class with Properties and Methods


  class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}

const person = new Person('Alias', 25);
person.sayHello(); // Output: Hello, my name is Alias and I'm 25 years old.

In this example, we define a Person class with a constructor that sets the name and age properties of the object. The class also has a sayHello method that logs a greeting with the person's name and age. We create an instance of the Person class and invoke the sayHello method.


Class Inheritance


   class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  } }
  
class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
  speak() {
    console.log(`${this.name} barks!`);
  } }
  
const dog = new Dog('Blody', 'Labrador');
dog.speak(); // Output: Blody barks!

In this example, we have a base Animal class with a name property and a speak method. The Dog class extends the Animal class and adds a breed property and overrides the speak method. The super keyword is used to call the parent class's constructor. We create a dog object and invoke the speak method, which logs a breed-specific bark.


Static Methods and Getters/Setters


 class Circle {
  constructor(radius) {
    this.radius = radius;
  }

  static createDefault() {
    return new Circle(1);
  }

  get diameter() {
    return this.radius * 2;
  }

  set diameter(value) {
    this.radius = value / 2;
  }

  get area() {
    return Math.PI * this.radius ** 2;
  } }

const circle = Circle.createDefault();
console.log(circle.diameter); // Output: 2
circle.diameter = 4;
console.log(circle.radius); // Output: 2
console.log(circle.area); // Output: 12.566370614359172

In this example, we define a Circle class that represents a circle with a radius property. The class includes a static method createDefault to create a circle with a default radius. We also have getters and setters for diameter, which computes the diameter based on the radius, and an area getter that calculates the circle's area. We create a circle object using the static method, modify the diameter using the setter, and access the radius and area using the getters.


Feel free to copy the code and experiment with our javascript compiler


Output:

×