OOP exercises, practice, solution.

Click Below questions to see solutions

Prototype based

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

//Adding prototype to the Person function
Person.prototype.displayDetails = function() {
    console.log(`Name: ${this.name}, Age: ${this.age}, Country: ${this.country}`);
}

// Create instances of the Person function
const person1 = new Person('Bruce Lee', 32, 'Hong Kong-American');
const person2 = new Person('James Allen', 47, 'England');
const person3 = new Person('Mortimer J. Adler', 98, 'American');

//calling the method in (Person constructor function) prototype 
person1.displayDetails();
person2.displayDetails();
person3.displayDetails();

Class based

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

    displayDetails() {
        console.log(`Name: ${this.name}, Age: ${this.age}, Country: ${this.country}`);
    }
}

// Create instances of the Person class
const person1 = new Person('Bruce Lee', 32, 'Hong Kong-American');
const person2 = new Person('James Allen', 47, 'England');
const person3 = new Person('Mortimer J. Adler', 98, 'American');

person1.displayDetails();
person2.displayDetails();
person3.displayDetails();