Prototype in javascript

Topics in this blog :
1 . Introduction to Prototypes
2.Prototype chain
3.Creating Objects with Prototype
Introduction to Prototypes
The general meaning of a prototype is the first model or design of something from which other models are developed. If, in the future, a new product is created, it usually includes the design or features of the original prototype. In this way, the prototype serves as the base or foundation that guides all upcoming products.
Example:
Let’s take a car company or any product manufacturing company. They are always trying to build something new—like adding features, improving design, or upgrading services. However, during this process, they don’t need to change the basic functionality, because that core foundation stays the same. which is as it's is same
the same thing in this case is prototype .
In javaScript, the prototype is a container for methods and properties. When methods or properties are added to the prototype of a function, array, or string, they become shared by all instances of that particular object type. Prototype in general can be understood as a mould and all its instances can be considered as the car made from it.
All method mentioned in object prototype is also available in new instances for Example:
In this Example we can clearly see how a prototype is used by their instance now any new object also have this access .like car example now all object shared this methods .
Behinds the seens (in Background )
Prototype Chaining:
When you try to access a property or method on an object, JavaScript first checks whether that property or method exists on the object itself. If it doesn’t find it, it searches the prototype of that object. This process continues until you find the desired property/method or until you reach the “Object.prototype” object, the last in the prototype chain.
function Person(name) {
this.name = name; }
Person.prototype.greet = function() {
console.log("Hello, my name is " + this.name);
};
const alice = new Person("Alice"); alice.greet(); // Output: Hello, my name is Alice
conclusion
"A prototype is a hidden internal property of an object. When we create a new object using a constructor function, the new object inherits from that constructor’s prototype. This is known as prototype inheritance, and it allows all instances to share common properties and methods."
Subscribe to my newsletter
Read articles from Prince Sah directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
