How does JavaScript .prototype work?

How does JavaScript .prototype work?

In JavaScript, the prototype property is used to create objects that share common properties and methods. Every JavaScript object has a prototype property, which is an object that contains properties and methods that the object can inherit.

When you create a new object using the new keyword and a constructor function, JavaScript will automatically create a prototype object for that object, and set the object’s __proto__ property to point to the prototype object.

You can add properties and methods to the prototype object using the .prototype property of the constructor function, and these properties and methods will be available to all objects created using that constructor function. Here’s an example:

function MyObject() {}
MyObject.prototype.name = "default";
MyObject.prototype.getName = function() {
    return this.name;
};
let obj1 = new MyObject();
console.log(obj1.getName()); // "default"

When you try to access a property on an object, JavaScript first looks for that property on the object itself. If it doesn’t find the property, it looks for it on the object’s prototype object, and so on, until it either finds the property or reaches the end of the prototype chain. This is called “prototype chain” and it is how JavaScript’s inheritance works.

You can also change the prototype of an object by reassigning the value of its __proto__ property, but it is not recommended as it is a non-standard way of doing it. The way to change the prototype of an object is using the Object.create() method

let obj2 = Object.create(obj1);

Now the obj2 prototype is the obj1 and it will have access to all of its properties and methods.

It’s also possible to add properties and methods directly on the object itself, these properties and methods will be specific to that object, and won’t affect other objects created from the same prototype, this is called “shadowing”.

prototype property allows JavaScript to have a mechanism for sharing properties and methods across objects, making it easier to manage and maintain code by avoiding repetitive coding and making the code more organized.

Leave a Reply