Basics

Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of "objects", which can contain data and behaviour in the form of properties (data) and methods (functions).

In JavaScript, objects can be created in a few different ways. One way is to use the object literal syntax:

const person = {
  name: 'John',
  age: 30,
  sayHello: function() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
};

person.sayHello(); // "Hello, my name is John and I am 30 years old."

Another way to create objects is to use a constructor function:

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

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};

const person1 = new Person('John', 30);
person1.sayHello(); // "Hello, my name is John and I am 30 years old."

In OOP, objects can also be created using classes, which are templates for creating objects. Classes can be used to define the properties and methods that will be shared by all objects created from the class, as well as to define the relationships between different objects.

Here is an example of using classes to create objects:

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

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

const person1 = new Person('John', 30);
person1.sayHello(); // "Hello, my name is John and I am 30 years old."

OOP is a powerful programming paradigm that allows developers to model real-world objects and their relationships in code, making it easier to design, understand, and maintain complex software systems.

Last updated