KandZ – Tuts

We like to help…!

JavaScript 29 🧬 Prototype

a - What is the prototype
a prototype is a mechanism that allows you to add properties and methods to objects.
Every JavaScript function has a prototype property, which refers to an object known as the "prototype object."
This prototype object serves as a template from which all instances of the function's objects are created.
how prototypes work in JavaScript:
1. Function Declaration: When you declare a function, it automatically gets a prototype property.
2. Creating Objects: When you create an object using a constructor function that object inherits properties and methods from the constructor's prototype.
3. Inheritance: The newly created object has a hidden property called [[Prototype]] that points to the constructor function's prototype object.

b - Accessing, modifying Prototype and key points
Prototype Chain: When you try to access a property or method on an object, JavaScript first looks for it on the object itself.
If it doesn't find it, it looks up the prototype chain until it finds the property/method or reaches the end of the chain (i.e., null).
Efficiency: By defining methods on the prototype, you save memory because the method is shared across all instances rather than being duplicated for each instance.
Inheritance: Prototypes allow for inheritance, where objects can inherit properties and methods from other objects.
Understanding prototypes is crucial for effective JavaScript programming, especially when dealing with object-oriented programming and inheritance.
Accessing the Prototype:
You can access an object's prototype using the Object.getPrototypeOf() method or the deprecated _proto_ property
Modifying the Prototype:
You can add, modify, or delete properties and methods on a prototype object at any time.
However, be cautious when modifying built-in objects' prototypes (e.g., Array, String) as it can lead to unexpected behavior.

c - Prototype examples
function Person(name, age) {} → Constructor function
Person.prototype.greet = function() {} → Adding a method to the prototype
const person1 = new Person('Alice', 30); → Creating objects using the constructor
person1.greet(); → Use of the greet method
console.log(person1.__proto__ === Person.prototype); → accessing the prototype
Array.prototype.sum = function() {} → Adding a new method to the Array prototype

Leave a Reply