Flat Preloader Icon

JS Prototype

In JavaScript, the prototype property is a fundamental concept that plays a crucial role in implementing inheritance and sharing behavior between objects. It’s used to add properties and methods to objects through a mechanism called prototypal inheritance.

Prototype Chain:

  • Every JavaScript object has a prototype, which is an object from which it inherits properties and methods.
  • When you access a property or method on an object, JavaScript first looks for that property or method directly on the object. If it doesn’t find it, it looks at the object’s prototype, and if it’s not found there, it continues up the prototype chain until it reaches the top-level prototype (Object.prototype).

prototype Property:

  • The prototype property is a reference to the prototype object of a constructor function. It’s automatically created and assigned to constructor functions when they are defined.
  • When you create a new object using the new keyword with a constructor function, the new object’s prototype is set to the constructor function’s prototype property.
				
					// Constructor function
function Person(name) {
    this.name = name;
}

// Adding a method to the Person prototype
Person.prototype.greet = function() {
    console.log("Hello,
    my name is " + this.name);
};

// Creating objects using the Person constructor
let person1 = new Person("Alice");
let person2 = new Person("Bob");

// Accessing method defined in the prototype
person1.greet(); 
// Output: Hello, my name is Alice
person2.greet(); 
// Output: Hello, my name is Bob

				
			

Inheritance:

  • Prototypal inheritance allows objects to inherit properties and methods from their prototype.
  • When you try to access a property or method on an object, JavaScript looks for it in the object’s own properties first. If it’s not found, it continues up the prototype chain until it finds it or reaches the top-level prototype (Object.prototype).

Prototype vs. __proto__:

  • The prototype property is used by constructor functions to define properties and methods that will be inherited by objects created with the constructor.
  • The __proto__ property is a reference to the prototype of an object. It’s a non-standard way to access an object’s prototype and is not recommended for use in production code

Use Cases:

  • Implementing inheritance and sharing behavior between objects.
  • Adding methods or properties to all instances of a constructor function.