Loading...

Go Back

Next page
Go Back Course Outline

JavaScript Full Course


Objects and Prototypes in JavaScript

Object-Oriented Programming (OOP) is a programming style based on the concept of "objects" — data structures that contain properties and methods. JavaScript supports OOP using objects and classes.

Key OOP Concepts in JavaScript:
  • Class – A blueprint for creating objects.
  • Object – An instance of a class.
  • Constructor – A special method used to initialize objects.
  • Method – A function defined inside a class.
  • Inheritance – One class can inherit properties and methods from another.
  • Encapsulation – Keeping data safe and hidden inside objects.
  • Polymorphism – Different classes can define the same method differently.
Example:
// Define a class
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

// Create an object
const dog = new Animal("Dog");
dog.speak(); // Output: Dog makes a sound.
Inheritance Example:
class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const myDog = new Dog("Rex");
myDog.speak(); // Output: Rex barks.
Tip:

OOP helps you organize your code better, reuse it efficiently, and make large projects easier to manage.

1. Creating Objects

There are multiple ways to create objects in JavaScript: object literals, constructors, and Object.create().

1.1 Object Literals

                        const person = {
                            name: "Alice",
                            age: 30,
                            greet: function() {
                                console.log("Hello, " + this.name);
                            }
                        };
                        
                        person.greet();  // Output: Hello, Alice
                                
Output:
Hello, Alice

1.2 Constructors

You can create objects using a constructor function.

                        function Person(name, age) {
                            this.name = name;
                            this.age = age;
                            this.greet = function() {
                                console.log("Hello, " + this.name);
                            };
                        }
                        
                        const person1 = new Person("Bob", 25);
                        person1.greet();  // Output: Hello, Bob
                                
Output:
Hello, Bob


1.3 Object.create()

The Object.create() method creates a new object with the specified prototype object.

                        const personPrototype = {
                            greet: function() {
                                console.log("Hello, " + this.name);
                            }
                        };
                        
                        const person2 = Object.create(personPrototype);
                        person2.name = "Charlie";
                        person2.greet();  // Output: Hello, Charlie
                                
Output:
Hello, Charlie

2. Object Properties and Methods

Objects can contain properties (key-value pairs) and methods (functions).

2.1 Object Properties

                        const car = {
                            make: "Toyota",
                            model: "Corolla",
                            year: 2020
                        };
                        
                        console.log(car.make);  // Output: Toyota
                        console.log(car["model"]);  // Output: Corolla
                                
Output:
Toyota
Corolla

2.2 Object Methods

                        const car = {
                            make: "Toyota",
                            model: "Corolla",
                            year: 2020,
                            getCarInfo: function() {
                                return `${this.year} ${this.make} ${this.model}`;
                            }
                        };
                        
                        console.log(car.getCarInfo());  // Output: 2020 Toyota Corolla
                                
Output:
2020 Toyota Corolla

3. The this Keyword

The this keyword refers to the object that the function is a method of.

                        const person = {
                            name: "David",
                            greet: function() {
                                console.log("Hello, " + this.name);
                            }
                        };
                        
                        person.greet();  // Output: Hello, David
                                
Output:
Hello, David

4. Prototypes and Inheritance

Prototypes allow objects to inherit properties and methods from other objects.

                        function Animal(name) {
                            this.name = name;
                        }
                        
                        Animal.prototype.speak = function() {
                            console.log(this.name + " makes a sound");
                        };
                        
                        const dog = new Animal("Rex");
                        dog.speak();  // Output: Rex makes a sound
                                
Output:
Rex makes a sound

5. Prototype Chain

JavaScript objects have a prototype, and that prototype can have its own prototype, forming a chain.

                        function Animal(name) {
                            this.name = name;
                        }
                        
                        Animal.prototype.speak = function() {
                            console.log(this.name + " makes a sound");
                        };
                        
                        function Dog(name, breed) {
                            Animal.call(this, name);  // Call the Animal constructor
                            this.breed = breed;
                        }
                        
                        Dog.prototype = Object.create(Animal.prototype);  // Set Dog's prototype to be an instance of Animal
                        Dog.prototype.constructor = Dog;
                        
                        Dog.prototype.bark = function() {
                            console.log(this.name + " barks");
                        };
                        
                        const dog = new Dog("Buddy", "Golden Retriever");
                        dog.speak();  // Output: Buddy makes a sound
                        dog.bark();   // Output: Buddy barks
                                
Output:
Buddy makes a sound
Buddy barks


6. Object-Oriented Programming (OOP) Principles

JavaScript supports Object-Oriented Programming (OOP) principles like encapsulation, inheritance, and polymorphism.

6.1 Encapsulation

Encapsulation means grouping related data and the functions that manipulate that data within a class.

Information hiding:
It also involves hiding the internal implementation details of a class from the outside world.

Controlled access:
Encapsulation allows controlled access to the object's data and behavior, often using access modifiers like private or protected to restrict direct access to certain attributes or methods.

                        function Person(name, age) {
                            this.name = name;
                            this.age = age;
                        
                            this.getDetails = function() {
                                return `${this.name} is ${this.age} years old.`;
                            };
                        }
                        
                        const person = new Person("John", 25);
                        console.log(person.getDetails());  // Output: John is 25 years old.
                                
Output:
John is 25 years old.

6.2 Polymorphism

Polymorphism means "many forms" and refers to the ability of an object or method to exhibit different behaviors depending on the specific object it's acting on or the context in which it's used.

Method overriding:
A common example of polymorphism is method overriding, where a subclass provides a specific implementation of a method inherited from a parent class.

Method overloading:
Another form of polymorphism is method overloading, where multiple methods with the same name can have different parameters, allowing them to handle different input types or scenarios.

Benefits:
Polymorphism allows for flexible and extensible code, enabling code to be reused and adapted to different types of objects or situations.

                        function Animal(name) {
                            this.name = name;
                        }
                        
                        Animal.prototype.speak = function() {
                            console.log(this.name + " makes a sound");
                        };
                        
                        function Dog(name) {
                            Animal.call(this, name);
                        }
                        
                        Dog.prototype = Object.create(Animal.prototype);
                        Dog.prototype.speak = function() {
                            console.log(this.name + " barks");
                        };
                        
                        function Cat(name) {
                            Animal.call(this, name);
                        }
                        
                        Cat.prototype = Object.create(Animal.prototype);
                        Cat.prototype.speak = function() {
                            console.log(this.name + " meows");
                        };
                        
                        const dog = new Dog("Rex");
                        const cat = new Cat("Whiskers");
                        
                        dog.speak();  // Output: Rex barks
                        cat.speak();  // Output: Whiskers meows
                                
Output:
Rex barks
Whiskers meows
Go Back

Next page