Prototype

JavaScript Prototype Tutorial

Table of Contents

  1. Introduction to Prototypes in JavaScript

  2. What is a Prototype?

  3. The Prototype Chain

  4. Understanding __proto__ and prototype

  5. Adding Methods and Properties to the Prototype

  6. Inheriting Properties and Methods Using Prototypes

  7. Modifying Built-in Prototypes

  8. Checking for Properties in Prototypes

  9. Practical Examples

    • Creating Custom Methods with Prototypes

    • Inheriting Properties with Prototypes

    • Modifying the Array Prototype

  10. Prototype vs. Class: Understanding the Differences

  11. Conclusion


1. Introduction to Prototypes in JavaScript

Welcome to the Codes with Pankaj tutorial on JavaScript Prototypes! In this tutorial, we will explore the concept of prototypes in JavaScript and how they are used to implement inheritance and extend objects. Let’s dive in!

Prototypes are a fundamental part of JavaScript's object-oriented model. They allow objects to inherit properties and methods from other objects, enabling code reuse and extending functionality.

2. What is a Prototype?

In JavaScript, every object has a prototype. A prototype is simply another object from which the current object inherits properties and methods. When you try to access a property or method on an object, JavaScript will first look at the object itself. If it doesn't find the property or method there, it will look at the object's prototype.

Example:

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

Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}.`);
};

let person1 = new Person("Alice");
person1.greet();  // Output: Hello, my name is Alice.

In this example, the greet method is defined on the Person prototype, and it is inherited by person1.

3. The Prototype Chain

The prototype chain is a series of links between objects. When you access a property on an object, JavaScript will search up the prototype chain until it finds the property or reaches the end of the chain.

Example:

let obj = {};
console.log(obj.toString());  // Output: [object Object]

In this example, obj doesn't have a toString method, but JavaScript finds it in the Object.prototype, which is part of the prototype chain.

4. Understanding __proto__ and prototype

  • __proto__: Every object in JavaScript has an internal property called __proto__, which points to the prototype object from which it inherits properties and methods.

Example:

let person1 = new Person("Alice");
console.log(person1.__proto__ === Person.prototype);  // Output: true
  • prototype: When you create a function in JavaScript, it automatically gets a prototype property. This prototype property is an object that will be used as the prototype for all instances created by that function.

Example:

console.log(Person.prototype);  // Output: Person {}

5. Adding Methods and Properties to the Prototype

You can add methods and properties to an object's prototype, and all instances of that object will inherit those methods and properties.

Example:

Person.prototype.sayGoodbye = function() {
    console.log(`${this.name} says goodbye.`);
};

let person2 = new Person("Bob");
person2.sayGoodbye();  // Output: Bob says goodbye.

6. Inheriting Properties and Methods Using Prototypes

You can use prototypes to implement inheritance in JavaScript. This allows objects to inherit properties and methods from other objects.

Example:

function Animal(name) {
    this.name = name;
}

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

function Dog(name) {
    Animal.call(this, name);  // Inherit properties
}

Dog.prototype = Object.create(Animal.prototype);  // Inherit methods
Dog.prototype.constructor = Dog;

Dog.prototype.speak = function() {
    console.log(`${this.name} barks.`);
};

let dog = new Dog("Buddy");
dog.speak();  // Output: Buddy barks.

7. Modifying Built-in Prototypes

JavaScript allows you to modify the prototypes of built-in objects, such as Array, String, and Object. However, this should be done with caution, as it can affect all instances of that object.

Example:

Array.prototype.first = function() {
    return this[0];
};

let arr = [1, 2, 3];
console.log(arr.first());  // Output: 1

8. Checking for Properties in Prototypes

You can check whether a property exists directly on an object or in its prototype using the hasOwnProperty() method and the in operator.

Example:

console.log(person1.hasOwnProperty('name'));  // Output: true
console.log(person1.hasOwnProperty('greet'));  // Output: false
console.log('greet' in person1);  // Output: true

9. Practical Examples

Creating Custom Methods with Prototypes

function Car(brand, model) {
    this.brand = brand;
    this.model = model;
}

Car.prototype.getCarInfo = function() {
    return `${this.brand} ${this.model}`;
};

let car1 = new Car("Toyota", "Camry");
console.log(car1.getCarInfo());  // Output: Toyota Camry

Inheriting Properties with Prototypes

function Animal(name) {
    this.name = name;
}

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

function Cat(name) {
    Animal.call(this, name);  // Inherit properties
}

Cat.prototype = Object.create(Animal.prototype);  // Inherit methods
Cat.prototype.constructor = Cat;

let cat = new Cat("Whiskers");
cat.speak();  // Output: Whiskers makes a sound.

Modifying the Array Prototype

Array.prototype.last = function() {
    return this[this.length - 1];
};

let numbers = [1, 2, 3];
console.log(numbers.last());  // Output: 3

10. Prototype vs. Class: Understanding the Differences

While both prototypes and classes can be used to create objects and implement inheritance, they have different syntaxes and concepts:

  • Prototypes: The traditional way to create and extend objects in JavaScript. Objects inherit directly from other objects.

  • Classes: A more modern syntax introduced in ES6, providing a more familiar and concise way to work with object-oriented patterns.

11. Conclusion

In this detailed tutorial, we've explored the concept of prototypes in JavaScript, which are essential for implementing inheritance and extending objects. By understanding prototypes, you can create more efficient and reusable code in your JavaScript applications.

For more tutorials and examples, visit www.codeswithpankaj.com! Happy coding!


Last updated