start learning
Image 1
403079745004747

Objects JavaScript Object-Oriented Programming (OOP)


Simple Person Object


const person = {
  name: 'John',
  age: 25,
  greet() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
};

person.greet(); // Output: Hello, my name is John and I'm 25 years old.

This is a basic example of an object representing a person. It has two properties, name and age, which store the person's name and age, respectively. The greet method is a function that logs a greeting using the person's name and age.


Book Object with Constructor Function


function Book(title, author, year) {
  this.title = title;
  this.author = author;
  this.year = year;
}

Book.prototype.getDetails = function() {
  console.log(`${this.title} written by ${this.author} in ${this.year}`);
};

const book1 = new Book('The Great Gatsby', 'F. Scott Fitzgerald', 1925);
book1.getDetails(); // Output: The Great Gatsby written by F. Scott Fitzgerald in 1925.

This example demonstrates creating a Book object using a constructor function. The constructor function accepts parameters for title, author, and year and assigns them as properties of the object. The getDetails method is added to the Book prototype and can be called on any book object to log the book's details.


Complex Car Object with Prototypal Inheritance


 function Vehicle(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

Vehicle.prototype.getDetails = function() {
  console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}`);
};

function Car(make, model, year, color) {
  Vehicle.call(this, make, model, year);
  this.color = color;
}

Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;

Car.prototype.getColor = function() {
  console.log(`The color of the car is ${this.color}`);
};

const car1 = new Car('Toyota', 'Corolla', 2021, 'Red');
car1.getDetails(); // Output: Make: Toyota, Model: Corolla, Year: 2021.
car1.getColor(); // Output: The color of the car is Red.

This example demonstrates object-oriented concepts like inheritance and constructor chaining. The Vehicle constructor function creates a base object for vehicles, while the Car constructor function inherits from Vehicle. The Car constructor calls the Vehicle constructor using Vehicle.call(this, make, model, year). The Car prototype is set to a new object created from Vehicle.prototype, and its constructor is set back to Car. Additional methods, such as getColor, can be added to the Car prototype and accessed by instances of the Car object.


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


Output: